How to use useReducer React hook

Find out what the useReducer React hook is for and how to use it!

Since the introduction of Reacthook, I have completed multiple projects with them and they are great.

Removing all class-based components will make the code feel more "real" JavaScript. The functional component can finally manage the state.

Look at mineIntroduction to React hooksFirst of all, if you are a novice to them.

One of the hooks I sometimes use isuseReducer.

import React, { useReducer } from 'react'

This hook is used to manage state. A bit likeuseState, But more complicated.

This is the key difference between the twouseStatewithuseReducer: withuseReducer,Change the state by passing a messageInstead of calling the updater function.

If you know howReduxThe principle is basically the same. The reducer is a pure function that can calculate the next state based on the previous state and the dispatched action.

(currentState, action) => newState

What does "pure function" mean? Pure functions accept input and return output without changing the input or anything else. This means that the reducer will return to a completely new state, which will replace the previous state.

The reducer should:

  • Never change its argument
  • Never produce side effects (no API call will change anything)
  • Never call impure functions, these functions will change their output based on factors other than the input (for example,Date.now()orMath.random())

No reinforcement, but you should follow the rules. This has a nice benefit: reducing agents are easier to test because they have no side effects.

This allows centralized state management, allows components to modify them by sending messages, and also allows you to use (and change) more complex states in the component.

Let's use a counter component as an example.

useReducerAccept the reducer function and initial state value as parameters. In this case, our state is an integer, starting from 0:

const Counter = () => {
  const [state, dispatch] = useReducer(reducer, 0)
}

A reducer is a function, as mentioned above, it accepts the current state and an action, and the value can be any type of value you want. In this case, it is a string:

const reducer = (state, action) => {
  switch (action) {
    case 'INCREMENT':
      return state + 1
    case 'DECREMENT':
      return state - 1
    default:
      throw new Error()
  }
}

We also make the component output someJSXTo make this simple application work:

const Counter = () => {
  const [count, dispatch] = useReducer(reducer, 0)
  return (
    <>
      Counter: {count}
      <button onClick={() => dispatch('INCREMENT')}>+</button>
      <button onClick={() => dispatch('DECREMENT')}>-</button>
    </>
  )
}

This is the complete example on Codepen:

Look at the penReact useReducer hookBy Flavio Copes (@flaviocopes) InCipher pen.

Tech Wiki Online!