Performance: Common lifting state patterns
This affects interaction responsiveness and rendering speed by controlling how often components re-render when state changes.
function Parent() { const [count, setCount] = React.useState(0); return ( <> <ChildA setCount={setCount} /> <ChildB count={count} /> </> ); } const ChildA = React.memo(({ setCount }) => { console.log('ChildA rendered'); return <button onClick={() => setCount(c => c + 1)}>Increment</button>; }); const ChildB = React.memo(({ count }) => { console.log('ChildB rendered'); return <div>{count}</div>; });
function Parent() { const [count, setCount] = React.useState(0); return ( <> <ChildA count={count} setCount={setCount} /> <ChildB count={count} setCount={setCount} /> </> ); } function ChildA({ count, setCount }) { return <button onClick={() => setCount(count + 1)}>Increment</button>; } function ChildB({ count }) { return <div>{count}</div>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Lifting state too high | Many components re-render | Multiple reflows per update | High paint cost due to many updates | [X] Bad |
| Lifting state minimally | Only necessary components re-render | Single reflow per update | Low paint cost | [OK] Good |
lifting state means moving state to a common parent component.name={value}. To pass state and updater, use state={state} and setState={setState}.<Child state={state} setState={setState} /> correctly passes both as props. Others misuse assignment or call functions incorrectly.function Parent() {
const [count, setCount] = React.useState(0);
return (
<>
<Display count={count} />
<Button onClick={() => setCount(count + 1)} />
</>
);
}function Parent() {
const [value, setValue] = React.useState('');
return <Child value={value} setValue={value} />;
}value={value} correctly but setValue={value} incorrectly passes the state value instead of the updater function.setValue={setValue} to allow Child to update state.InputA and InputB, both need to update and display the same text value. Which pattern correctly lifts state to their parent to keep them in sync?Pass the test and this pattern moves unknown