CodeBlanks Logo Icon CodeBlanks

useReducer

Learn complex state management with useReducer.

What is useReducer?

useReducer is a hook for complex state management. It is like useState but it updates state through a reducer function. You call it as const [state, dispatch] = useReducer(reducer, initialState).

useReducer is useful when you have several related state fields or complex transition logic. With dispatch you send an action; the reducer looks at it and returns the new state. This pattern puts state changes in one central place; it makes debugging and testing easier. It is a Redux-like approach turned into a React hook.

Three core pieces

useReducer works with three core pieces. First the reducer: a function that takes the current state and an action and returns the new state. Second the initial state: the starting value of state. Third dispatch: the function that sends actions.

A typical flow: when a component notices an event it calls dispatch({ type: "increment" }). React passes this action to the reducer; the reducer computes and returns the new state. The component re-renders with the new state. This flow makes state changes predictable and traceable.

Practice Call useReducer

Write a Counter component. Call useReducer with reducer and initialState; take state and dispatch from the result. Define reducer and initialState outside the component. The component returns <Text>Counter</Text>.

Starter code

App.js
// Import useReducer

// Define the reducer function; takes state and action
// Define initialState as 0

function Counter() {
  // Call useReducer with reducer and initialState

  return <Text>Counter</Text>;
}

Sample solution

App.js
import { useReducer } from "react";
import { Text } from "react-native";

function reducer(state, action) {
  return state;
}

const initialState = 0;

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return <Text>Counter</Text>;
}

Questions and answers

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

1 What is useReducer used for?

App.js
const [state, dispatch] = useReducer(reducer, initialState);
  • For AsyncStorage
  • To style the component
  • For navigation
  • For complex state management Correct answer

Explanation: useReducer is used for complex state management.

2 Call useReducer

Question
const [state, dispatch] = ____(reducer, initialState);
Answer
const [state, dispatch] = useReducer(reducer, initialState);

Explanation: useReducer takes reducer and initialState.

3 Match each piece to its role

Term Meaning
reducer Computes state
initialState Starting value
dispatch Sends an action
action Describes an event

All lessons in Intermediate