Advanced State with Reducers

My reading notes for Code Fellows


Advanced State with Reducers

useReducer hook

Name an alternative to the useState Hook. useReducer is an alternative to useState. It accepts a reducer of type (state, action) => newState, and returns the current state paired with a dispatch method.

Why might the useReducer Hook be preferable to the useState Hook? useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. useReducer also lets you optimize performance for components that trigger deep updates because you can pass dispatch down instead of callbacks.

What are two ways to set the initial state?

  1. Specifying the initial state There are two different ways to initialize useReducer state. You may choose either one depending on the use case. The simplest way is to pass the initial state as a second argument:
const [state, dispatch] = useReducer(
  reducer,
  {count: initialCount}
);
  1. Lazy initialization You can also create the initial state lazily. To do this, you can pass an init function as the third argument. The initial state will be set to init(initialArg).

It lets you extract the logic for calculating the initial state outside the reducer. This is also handy for resetting the state later in response to an action:

Ultimate Guide to useReducer

In terms of state, what does useReducer expect to receive as a parameter? The useReducer Hook is used to store and update states, just like the useState Hook. It accepts a reducer function as its first parameter and the initial state as the second.

What does useReducer return? useReducer returns an array that holds the current state value and a dispatch function to which you can pass an action and later invoke it

Explain dispatch to a non-technical recruiter. Its job is to sends the type of action to the reducer function, which updates state.