CodeBlanks Logo Icon CodeBlanks

Summary - Context deep dive

Make cart state global with context + useReducer.

Summary - Context deep

In this group you learned to split context for performance, combine it with useReducer, and write guard hooks against the null default danger. Now you can safely manage large state.

The recipe: separate what changes often from what doesn't, write a custom useXContext hook per context, throw errors early and meaningfully. These three steps keep global state clean and fast.

In the next step you'll write a CartProvider combining two contexts + reducer for a cart.

Practice CartProvider skeleton

Complete the skeleton. Write a CartProvider component. Call useReducer(cartReducer, { '{ items: [] }' }); destructure as [state, dispatch]. Return <CartStateContext.Provider value={ '{ state }' }> wrapping <CartDispatchContext.Provider value={ '{ dispatch }' }>{ '{ children }' }</CartDispatchContext.Provider></CartStateContext.Provider>. Export it.

Starter code

App.jsx
// Write the CartProvider component here

Sample solution

App.jsx
function CartProvider({ children }) {
  const [state, dispatch] = useReducer(cartReducer, { items: [] });
  return (
    <CartStateContext.Provider value={state}>
      <CartDispatchContext.Provider value={dispatch}>
        {children}
      </CartDispatchContext.Provider>
    </CartStateContext.Provider>
  );
}

export default CartProvider;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does a guard hook do?

  • Throw on null Correct answer
  • Update state
  • Access DOM
  • Skip useEffect

Explanation: Guard hook throws on null.

2 Match the context deep steps

Term Meaning
two contexts state + dispatch
useReducer Big state
guard hook null error
Provider Wraps

All lessons in Intermediate