UseReducer is based on the ideas of Redux and is an alternative to useState.

Features of the native useReducer

  1. Two parameters are received, the first is the Reducer function and the second is an initial state value.
  2. The useReducer returns an array. The first element of the array is the stored state and the second element is the method that triggered the action.

For more detailed information about the use of useReducer, see Hooks of useReducer and useContext

Handwritten useReducer

To implement useReducer, note the following:

  1. The Reducer function and the initial state values are user-defined.
  2. The Reducer function accepts two parameters, state and action.
  3. The useReducer function receives the reducer function and the initial state values.
  4. The useState hook function is called in the useReducer function.

Step 1: Use useState to get the initial state value passed by the user

const [state,setState] = useState(initialState);
Copy the code

Step 2: Execute the action sent by the user dispatch through setState

let dispatch = (action) = > {
    setState(reducer(state,action))
}
Copy the code

The first argument to an array is the state value, and the second state value is the method that sets the state

return [state,dispatch]
Copy the code

Complete implementation

import React,{useState} from 'react'
import ReactDOM from 'react-dom'

/ * * *@description: Handwritten useReducer *@param {*}
 * @return {*}* /

function useReducer(reducer,initialState) {
    const [state,setState] = useState(initialState);
    let dispatch = (action) = > {
        setState(reducer(state,action))
    }
    return [state,dispatch]
}

function App() {

    const reducer = (state,action) = > {
        switch (action.type) {
            case 'increment':
                return state + 1;
            case 'decrement':
                return state - 1;
            default:
                returnstate; }}const [count,dispatch] = useReducer(reducer,0)
    return (
        <>
            <h1>The current sum is: {count}</h1>
            <button onClick={()= >Dispatch ({type: 'increment'})}> Tap me +1</button>
            <button onClick={()= >Dispatch ({type: 'Decrement '})}> Click me -1</button>
        </>
    )
}

ReactDOM.render(<App />.document.querySelector('#root'));
Copy the code

Online implementation

  • CodeSandbox online implementation

Food for thought

  • Through the implementation of the useReducer, we can see that this is the same as the reducer realization thought in Redux. The programming thought sometimes has the same realization thought even in different application scenarios.

  • The key to an accurate understanding of the useReducer is to understand the flow of state in the useReducer.