Performance: Creating context
MEDIUM IMPACT
This affects interaction responsiveness and rendering speed by controlling how components share data without prop drilling.
const CountContext = React.createContext(); function App() { const [count, setCount] = React.useState(0); const value = React.useMemo(() => ({ count, setCount }), [count, setCount]); return ( <CountContext.Provider value={value}> <ComponentA /> <ComponentB /> <ComponentC /> </CountContext.Provider> ); } // Components only re-render when count changes, memoized value prevents unnecessary renders
const MyContext = React.createContext(); function App() { const [count, setCount] = React.useState(0); return ( <MyContext.Provider value={{ count, setCount }}> <ComponentA /> <ComponentB /> <ComponentC /> </MyContext.Provider> ); } // ComponentA, B, C all consume context and re-render on count change
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Context value recreated every render | Many components re-render | Multiple reflows if DOM changes | High paint cost due to many updates | [X] Bad |
| Memoized context value with useMemo | Only components using changed data re-render | Minimal reflows | Lower paint cost | [OK] Good |