CodeBlanks Logo Icon CodeBlanks

Action and state

Learn to define state transitions with action objects.

Action and state

An action is an object describing what happened: {type: "increment"}. You send this object to the reducer with dispatch; the reducer reads the type.

Example: in switch(action.type) a case "increment": return state + 1;. Each case returns a new state; the default returns the current state.

Actions can carry data too: {type: "add", payload: 5}.

Calling dispatch

To send an action you write dispatch({type: "increment"}). dispatch calls the reducer and stores the returned new state; React re-renders.

You can pass any action object to dispatch; the name is not fixed but the type field is conventionally required.

This structure separates logic from the component and makes tests easy.

Practice Incrementing reducer

Complete the skeleton. Write a reducer function; in switch(action.type) have case "increment": return state + 1; and default: return state;. Write a Counter component; import useReducer, define const [state, dispatch] = useReducer(reducer, 0);. Return <button onClick={() => dispatch({type: "increment"})}>{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 "increment": return state + 1;
    default: return state;
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, 0);
  return <button onClick={() => dispatch({ type: "increment" })}>{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 field does an action carry at least?

App.jsx
type matches in the reducer switch.
  • payload
  • value
  • id
  • type Correct answer

Explanation: type tells the action kind.

2 Action and state: fill in the missing part

Question
case "increment": return state + ____;
Answer
case "increment": return state + 1;

Explanation: Increment is state + 1.

3 Action and state: match the terms

Term Meaning
dispatch({type}) Send an action
switch(action.type) Match the type
case "x" One case
return state Default

All lessons in Beginner