MyInternships.in

State Management

React Context with useReducer

Combining context with useReducer gives a small global store with no dependencies: the reducer owns the transitions, the provider distributes state and dispatch, and any component can dispatch actions.


What is Context with useReducer in React?

Combining context with useReducer gives a small global store with no dependencies: the reducer owns the transitions, the provider distributes state and dispatch, and any component can dispatch actions.

Context with useReducer example

A cart store in about twenty lines
JSX
const CartContext = createContext(null);

function cartReducer(state, action) {
  switch (action.type) {
    case 'ADD':    return [...state, action.item];
    case 'REMOVE': return state.filter(i => i.id !== action.id);
    case 'CLEAR':  return [];
    default:       return state;
  }
}

export function CartProvider({ children }) {
  const [items, dispatch] = useReducer(cartReducer, []);
  const value = useMemo(() => ({ items, dispatch }), [items]);
  return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
}

export const useCart = () => useContext(CartContext);

How this works

dispatch is stable, so components that only dispatch never need to re-render when the items change — split state and dispatch into two contexts if you want that optimisation.

Key points to remember

  • Memoise the provider value or every consumer re-renders on each provider render.
  • Separate contexts for state and dispatch avoids re-rendering write-only components.
  • Fine up to moderate complexity; beyond that Redux Toolkit’s devtools and middleware pay off.

React Context with useReducer— Interview Questions & FAQs

Is context plus useReducer enough instead of Redux?+

For small and medium apps, usually yes. Redux Toolkit becomes worthwhile when you want time-travel devtools, middleware, or selective subscriptions that avoid re-rendering every consumer.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships