Search⌘ K
AI Features

React Advanced State

Explore advanced state management in React by learning to replace useState with useReducer. Understand how to create reducer functions that handle multiple actions, including adding and removing items, and gain practical skills for managing asynchronous data efficiently.

We'll cover the following...

All state management in this application makes heavy use of React’s useState Hook. More sophisticated state management gives you React’s useReducer Hook, though. Since the concept of reducers in JavaScript splits the community in half, we won’t cover it extensively here, but the exercises at the end of this section should give you plenty of practice.

We’ll move the stories state management from the useState hook to a new useReducer hook. First, introduce a reducer function outside of your components. A reducer function always receives state and action. Based on these two arguments, a reducer always returns a new state:

Node.js
const storiesReducer = (state, action) => {
if (action.type === 'SET_STORIES') {
return action.payload;
} else {
throw new Error();
}
};

A reducer action is often associated with a type. If this type matches a condition in the reducer, do something. ...