CodeBlanks Logo Icon CodeBlanks

Summary - useReducer

Combine reducer, dispatch and initial state to write a shopping cart.

Summary - useReducer

In this group you learned useReducer. The reducer is a pure function that computes state, dispatch sends an action, initial state is the starting value. You combine them to manage complex state.

Now you will build a shopping cart: the reducer handles the add-to-cart action; dispatch is called from a button. This is one of the most common real-world scenarios for useReducer. First you write the reducer, then the component; at the end you have a working cart.

Practice Write the cart reducer

Write a cartReducer function. state is an array (products). With switch (action.type) return [...state, action.payload] in the "add" case. In the default branch return state.

Starter code

App.js
// Write the cartReducer function
// state is an array; action is an object
// Use switch on action.type; write add and default branches

Sample solution

App.js
function cartReducer(state, action) {
  switch (action.type) {
    case "add":
      return [...state, action.payload];
    default:
      return state;
  }
}

Practice Write the cart component

Write a Cart component. Call useReducer with cartReducer and an empty array [] as initial state. When a button is pressed call dispatch({ type: "add", payload: "Apple" }). The component returns <Text>{state.length}</Text>.

Starter code

App.js
// Import useReducer

// Define the cartReducer (state is an array)
// In the add case return [...state, action.payload]

function Cart() {
  // Call useReducer with cartReducer and an empty array
  // On button press send the add action

  return <Text>Cart</Text>;
}

Sample solution

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

function cartReducer(state, action) {
  switch (action.type) {
    case "add":
      return [...state, action.payload];
    default:
      return state;
  }
}

function Cart() {
  const [state, dispatch] = useReducer(cartReducer, []);
  return (
    <>
      <Button onPress={() => dispatch({ type: "add", payload: "Apple" })} title="Add" />
      <Text>{state.length}</Text>
    </>
  );
}

Questions and answers

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

1 When is useReducer a good fit?

App.js
const [state, dispatch] = useReducer(reducer, initialState);
  • For complex state transitions Correct answer
  • Stil verisinde
  • AsyncStorage'da
  • Navigasyonda

Explanation: useReducer fits complex state transitions.

2 Match each piece to its role

Term Meaning
reducer Computes state
dispatch Sends an action
initialState Starting value
action.payload Extra data

3 Call useReducer

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

Explanation: useReducer takes cartReducer and an empty array.

All lessons in Intermediate