CodeBlanks Logo Icon CodeBlanks

Summary - useReducer pattern

Write a multi-step form wizard reducer and connect it.

Summary - useReducer pattern

In this group you learned what a reducer is, action types, composition, and the switch structure. Now you can manage complex state in an organized way.

The recipe: a separate reducer per state part, action types via constants, type in switch, combine with a root reducer. This gives a clear roadmap when useState falls short.

In the next step you'll write a Wizard component using useReducer for a multi-step form.

Practice Wizard skeleton

Complete the skeleton. Write a Wizard component. Call useReducer(wizardReducer, { '{ step: 0, data: {} }' }); destructure as [state, dispatch]. Return <div><p>Step: { '{ state.step }' }</p><button onClick={ '{ () => dispatch({ '{ type: "NEXT" }' }) }' }>Next</button></div>. Export it.

Starter code

App.jsx
import { useReducer } from "react";

// Write the Wizard component here

Sample solution

App.jsx
import { useReducer } from "react";

function Wizard() {
  const [state, dispatch] = useReducer(wizardReducer, { step: 0, data: {} });
  return (
    <div>
      <p>Step: {state.step}.</p>
      <button onClick={() => dispatch({ type: "NEXT" })}>Next</button>
    </div>
  );
}

export default Wizard;

Questions and answers

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

1 When is useReducer preferred?

  • For complex state transitions Correct answer
  • For simple counting
  • For CSS changes
  • In useEffect

Explanation: useReducer is preferred for complex state.

2 Match the useReducer pattern

Term Meaning
switch type branch
constant ADD
composition sub-reducer
useReducer [state, dispatch]

All lessons in Intermediate