๐—ฆ๐˜๐—ผ๐—ฝ ๐—จ๐—ป๐—ป๐—ฒ๐—ฐ๐—ฒ๐˜€๐˜€๐—ฎ๐—ฟ๐˜† ๐—ฅ๐—ฒ-๐—ฟ๐—ฒ๐—ป๐—ฑ๐—ฒ๐—ฟ๐˜€ ๐—ถ๐—ป ๐—ฅ๐—ฒ๐—ฎ๐—ฐ๐˜

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.

  1. 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.

  1. 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:

Build your providers defensively to keep your application fast.

Source: https://dev.to/iprajapatiparesh/stop-unnecessary-re-renders-architecting-react-context-4om8