The UseReducer Hook

UseReducer Hook

The useReducer hook is similar to the useState hook as they both manage states. While the useState manages non-complex state logic, the useReducer hook manages complex state logic involving multiple sub-values or interdependent states.

The useReducer hook helps in separating concerns: rendering and state management. It does so by taking the state management out of the component.

The useReducer hook accepts two arguments: the reducer function and the initialState. The hook returns an array of two items: the current state and the dispatch function.

import { useReducer } from 'react';
function MyComponent() { 
    const [state, dispatch] = useReducer(reducer, initialState); 
}

Reducer function

The reducer function is a pure function that accepts the current state and an action. The current state is the data present at a specific instance.

The reducer function is a function that we perform on our state to get new values. It usually has either a switch statement or an if/else statement that handles the various action types and returns a new state based on the selected action type.

initialState

The initialState is the value(s) the state is initialized with. We can call it the default state. It is returned as the 'state'(one of the items the useReducer hook returns).

Dispatch function

The dispatch function is what we call to update our state. Of course, we have to specify what action type we want to be executed. It accepts an object containing the action type we want to be executed. It then goes to our reducer function and checks if the action type specified in the dispatch function exists and executes it.

import { useReducer } from 'react';
const initialState = {count: 0}; // initial state

// reducer function
function reducer(state, action) { 
// can use a switch or if/else statement
switch (action.type) { 
case 'increment': 
    return {count: state.count + 1};
case 'decrement': 
    return {count: state.count - 1};
default: 
    throw new Error(); } 
}

function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<> 
    Count: {state.count}
    <button onClick={() => dispatch({type: 'decrement'})}>-</button>
    <button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
    );
}

The useReducer hook makes it easy to keep track of multiple pieces of state that rely on complex logic. The dispatch function in the useReducer hook eliminates the need for callbacks when dealing with nested components. It optimizes the performance of such components.

Helpful Resources: