CodeBlanks Logo Icon CodeBlanks

Summary - useReducer

Write a multi-action counter reducer and connect it to a component.

Summary - useReducer

In this group you learned useReducer. State is managed by a reducer pure function: (state, action) => newState. You send actions with dispatch.

Actions are {type, payload} objects; the reducer switches on the type. For complex state useReducer is cleaner than useState.

Later Redux will extend the same model; you built the base here.

Practice useReducer summary task

Complete the skeleton. Write a reducer function; in switch(action.type) have case "reset": return 0; and default: return state;. Write a Counter component; import useReducer, define const [state, dispatch] = useReducer(reducer, 0);. Return <button onClick={() => dispatch({type: "reset"})}>{state}</button>. Export it.

Starter code

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

// Define reducer and Counter here

Sample solution

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

function reducer(state, action) {
  switch (action.type) {
    case "reset": return 0;
    default: return state;
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, 0);
  return <button onClick={() => dispatch({ type: "reset" })}>{state}</button>;
}

export default Counter;

Questions and answers

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

1 Which is wrong?

App.jsx
The choice depends on complexity.
  • reducer is a pure function
  • useReducer is always better than useState Correct answer
  • an action carries type
  • dispatch sends an action

Explanation: For simple state useState may be better.

2 Summary - useReducer: match the terms

Term Meaning
reducer Pure function
dispatch Sends an action
type Action kind
switch Type matching

All lessons in Beginner