๐ฆ๐๐ผ๐ฝ ๐จ๐ป๐ป๐ฒ๐ฐ๐ฒ๐๐๐ฎ๐ฟ๐ ๐ฅ๐ฒ-๐ฟ๐ฒ๐ป๐ฑ๐ฒ๐ฟ๐ ๐ถ๐ป ๐ฅ๐ฒ๐ฎ๐ฐ๐
React Context helps you avoid prop drilling. You wrap your app in a Provider to send data to nested components.
But Context has a flaw called Value Reference Equality.
When you pass an object into a Provider, React checks it on every render. If you pass value={{ user, theme }}, React creates a new object in memory every time the parent renders.
React sees a new object. It thinks the data changed. This forces every component using that Context to re-render. In a large app, a simple theme toggle can trigger dozens of heavy components to recalculate. This kills your performance.
Fix this with two steps.
- Use useMemo
Junior developers often pass objects directly to the Provider. This causes constant re-renders.
Instead, wrap your object in useMemo. This tells React to keep the same object in memory. React will only create a new object if the specific data inside changes.
- Split your Context
For the best performance, separate your data from your functions. Create one Context for your state and a second Context for your dispatch functions.
React keeps state setter functions stable. If a component only needs to trigger an update, it will use the Dispatch Context. This component will not re-render when the data changes.
Why this matters:
- It stops redundant calculations.
- It keeps your UI smooth.
- It lowers CPU usage on the user device.
Build your providers defensively to keep your application fast.
Source: https://dev.to/iprajapatiparesh/stop-unnecessary-re-renders-architecting-react-context-4om8