Hackforge Academy

Category: react

Why Context Can Cause Extra Renders

Published on 27 Oct 2026

Explanation

When a provider receives a different value identity, React updates components that consume that context. Creating a new object on every render can trigger updates even if its fields have not changed.

Code:

function App() {
  const [user, setUser] = useState({ name: 'Maya' });
  const value = { user, setUser }; // New object every render
  return <UserContext.Provider value={value}><Page /></UserContext.Provider>;
}

Explanation

useMemo can preserve the provider value object while its dependencies stay the same. This avoids context updates caused solely by a newly allocated wrapper object.

Code:

const value = useMemo(() => ({ user, setUser }), [user]);

return (
  <UserContext.Provider value={value}>
    {children}
  </UserContext.Provider>
);

Explanation

If unrelated values change at different rates, placing them in separate contexts can prevent consumers of one value from updating whenever another value changes.

Code:

const ThemeContext = createContext('light');
const AuthContext = createContext(null);

function Providers({ children, theme, user }) {
  return (
    <ThemeContext.Provider value={theme}>
      <AuthContext.Provider value={user}>
        {children}
      </AuthContext.Provider>
    </ThemeContext.Provider>
  );
}

Explanation

When components only need to dispatch actions, a separate dispatch context can keep them from subscribing to state changes through the state context.

Code:

const StateContext = createContext(null);
const DispatchContext = createContext(null);

function Provider({ children }) {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <DispatchContext.Provider value={dispatch}>
      <StateContext.Provider value={state}>{children}</StateContext.Provider>
    </DispatchContext.Provider>
  );
}

Explanation

Move components that do not need context outside context-consuming subtrees where practical, and use the React Profiler to confirm the real bottleneck. Memoization cannot stop a component from updating when the context it consumes changes.

Code:

function Layout({ children }) {
  return <main><Header />{children}</main>;
}

function Page() {
  return <Layout><ContextConsumerSection /></Layout>;
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community