Performance: Sharing state between components
MEDIUM IMPACT
This affects interaction responsiveness and rendering speed when components update shared data.
const CountContext = React.createContext(); function Parent() { const [count, setCount] = React.useState(0); return ( <CountContext.Provider value={{ count, setCount }}> <ChildA /> <ChildB /> </CountContext.Provider> ); } function ChildA() { const { setCount } = React.useContext(CountContext); return <button onClick={() => setCount(c => c + 1)}>Increment</button>; } function ChildB() { const { count } = React.useContext(CountContext); return <div>{count}</div>; }
function Parent() { const [count, setCount] = React.useState(0); return ( <> <ChildA count={count} setCount={setCount} /> <ChildB count={count} /> </> ); } 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 |
|---|---|---|---|---|
| Prop drilling shared state | Many props passed down | Multiple re-renders on update | High paint cost due to many updates | [X] Bad |
| Context API with focused state | Minimal prop passing | Re-renders only subscribed components | Lower paint cost | [OK] Good |
| Global state with full object updates | Broad state access | Triggers many re-renders | High paint and layout cost | [X] Bad |
| Split contexts and memoized callbacks | Scoped updates | Minimal re-renders | Low paint and layout cost | [OK] Good |