React & Modern Frontend (445 Qs)•Part 1: Core React, JSX & Component Architecture (1 - 77)
What is Lifting State Up in React?
When several components need to share the same changing data then it is recommended to lift the shared state up to their closest common ancestor. That means if two child components share the same data from its parent, then move the state to parent instead of maintaining local state in both of the child components.
Practical Code Example
jsx
// Lifting State Up: Moving shared state to closest common ancestor
function Parent() {
const [temperature, setTemperature] = useState(25);
return (
<div>
<TemperatureInput temp={temperature} onTempChange={setTemperature} />
<BoilingVerdict celsius={temperature} />
</div>
);
}