⊗jsrtPmCoTOS 96 of 112 menu

Single Source of Truth in React

For any mutable data in a React app, there should be one source of truth. What this means is that if you have two states and one state can be calculated using the other, then one of the states is redundant and should be removed.

Let's discuss this with an example. Let's say you have two inputs: the first one takes the temperature in degrees Fahrenheit, and the second one takes the temperature in degrees Celsius. We want both inputs to be synchronized: when you enter the temperature in one input, it should change accordingly in the second.

The wrong approach would be to introduce two states: one for Fahrenheit temperature and one for Celsius. Why it is wrong: because one temperature is calculated from the other, which means that there should be one state as a data storage location.

Write an implementation of the described task.

A programmer wrote code that outputs the sum of the elements of an array:

function getSum(arr) { let res = 0; for (let elem of arr) { res += +elem; } return res; } function Calculator() { const [value, setValue] = useState(''); const [nums, setNums] = useState([1, 2, 3]); const [sum, setSum] = useState(6); // sum of elements of array nums function handleChange(event) { setValue(event.target.value); } function handleBlur(event) { setNums([...nums, event.target.value]); // add an element to the array setSum(getSum([...nums, event.target.value])); // we calculate the sum again } return <div> <p>{sum}</p> <input value={value} onChange={handleChange} onBlur={handleBlur} /> </div>; }

What's wrong with this code? Fix it.

Some programmer wrote code to edit array elements:

function App() { const [notes, setNotes] = useState([1, 2, 3, 4, 5]); const [editNum, setEditNum] = useState(null); const [value, setValue] = useState(''); const result = notes.map((note, index) => { return <p key={index} onClick={() => startEdit(index)}> {note} </p>; }); function startEdit(index) { setEditNum(index); setValue(notes[index]); // we write the text of the edited element in a separate state } function changeItem(event) { setValue(event.target.value); setNotes([...notes.slice(0, editNum), event.target.value,...notes.slice(editNum + 1)]); } return <div> {result} <input value={value} onChange={changeItem} /> </div>; }

What's wrong with this code? Fix it.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline