⊗jsrtPmCoLSU 95 of 112 menu

State Lifting in React

Often, multiple components need to reflect the same changing data. React recommends lifting shared state up to the nearest common ancestor. Let's look at an example.

Let's say we want to make a water temperature calculator. It will be an input where the user will enter the temperature, and a paragraph where the verdict will be output: water is liquid, water is solid, water is gaseous.

Let our calculator be a container component Calculator:

function Calculator() { return <div> </div>; }

Let's move the input for entering temperature to the TempInp component, and the paragraph with the verdict to the Verdict component:

function Calculator() { return <div> <Verdict /> <TempInp /> </div>; }

It is easy to understand that both TempInp and Verdict should have a state with a temperature. It is logical that it should be the same temperature: as data is entered into the input, the verdict should be displayed.

In such a case, it is recommended to use a technique called state lifting: the state common to two (or more) components is lifted up to their common parent.

In our case, it turns out that the temperature state should belong to the Calculator component, which will pass it to TempInp and Verdict as props:

function Calculator() { const [temp, setTemp] = useState(0); return <div> <Verdict temp={temp} /> <TempInp temp={temp} /> </div>; }

The TempInp component must have an input for changing the temperature. But since this temperature is a prop of this component, it cannot be changed directly in TempInp. It would be correct to pass a special function for changing the temperature from the Calculator component:

function Calculator() { const [temp, setTemp] = useState(0); function changeTemp(event) { setTemp(event.target.value); } return <div> <Verdict temp={temp} /> <TempInp temp={temp} changeTemp={changeTemp} /> </div>; }

By the way, you can, instead of introducing a new function, pass the setTemp function to the child component:

function Calculator() { const [temp, setTemp] = useState(0); return <div> <Verdict temp={temp} /> <TempInp temp={temp} setTemp={setTemp} /> </div>; }

Write an implementation of the TempInp and Verdict components.

Think of 3 problems that require state elevation. Write solutions to these problems.

enru