QA
Intermediate LevelReact JS & React 19

How do you optimize Context API to prevent widespread re-rendering?

❓ Interview Prompt: Explain Context re-rendering pitfalls, Context splitting (Data Context vs Dispatch Context), `useMemo` context values, and memoized selectors.

Whenever a Context value changes, ALL subscriber components using 'useContext' re-render, even if they only consume an unchanged portion of the context value!

Optimization Strategies:

1
Split Contexts: Separate volatile state data from stable action dispatchers into two providers ('StateContext' and 'DispatchContext').
2
Memoize Provider Value: Always wrap context value objects in 'useMemo' so identity remains stable across parent renders.

Code Implementation Example

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

function ContextProvider({ children }) {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <StateContext.Provider value={state}>
      {/* DispatchContext never changes identity! Components using dispatch never re-render on state updates! */}
      <DispatchContext.Provider value={dispatch}>
        {children}
      </DispatchContext.Provider>
    </StateContext.Provider>
  );
}
💡Splitting Context into State and Dispatch providers to eliminate unnecessary re-renders.
🎯 Interview Key Takeaway

Split Context into separate State and Dispatch providers to prevent action-only components from re-rendering on data updates.

#Context API#Optimization#re-rendering#Intermediate
Back to all React JS & React 19 Questions→

More React JS & React 19 Interview Questions

Beginner LevelReact JS & React 19

What is JSX and how does it work under the hood?

Beginner LevelReact JS & React 19

What is the difference between props and state in React?

Beginner LevelReact JS & React 19

How does the useState hook work and what is functional updater syntax?