Performance: Why lifting state is needed
This affects how efficiently React components update and share data, impacting interaction responsiveness and rendering speed.
function Parent() { const [count, setCount] = React.useState(0); return ( <> <ComponentA count={count} setCount={setCount} /> <ComponentB count={count} setCount={setCount} /> </> ); } // State is lifted and shared, keeping data consistent
function Parent() { const [countA, setCountA] = React.useState(0); const [countB, setCountB] = React.useState(0); return ( <> <ComponentA count={countA} setCount={setCountA} /> <ComponentB count={countB} setCount={setCountB} /> </> ); } // ComponentA and ComponentB cannot share state easily
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Duplicated state in multiple parents | Multiple state updates causing many DOM changes | Triggers reflows for each component update | Higher paint cost due to frequent updates | [X] Bad |
| Lifted state in common ancestor | Single state update triggers minimal DOM changes | Single reflow per update | Lower paint cost with batched updates | [OK] Good |
lifting state means moving state to a common parent component. What is the main reason for this?function Parent() {
const [count, setCount] = React.useState(0);
return (
<>
</>
);
}
function ChildA({ count }) {
return <div>Count: {count}</div>;
}
function ChildB({ setCount }) {
return <button onClick={() => setCount(c => c + 1)}>Increment</button>;
}ChildB is clicked?count is in Parent and passed down to ChildA and ChildB.setCount which updates count in Parent, causing ChildA to re-render with new count.Grandparent, Parent, and two siblings Child1 and Child2. Both children need to update and display the same piece of state. Where should you lift the state to and why?Child1 and Child2 share the Parent component as their closest common parent.Parent allows both children to access and update the same state easily without unnecessary complexity.Parent because it is the nearest common ancestor of the children -> Option APass the test and this pattern moves unknown