React - useReducer Hook

Published on
3 mins read
––– views

useReducer Hook

This hook lets you do what Redux can do, at least to some degree. The best thing about it is, you don't need to know Redux to use useReducer. Before we learn more about useReducer, we should talk about reducer.

Reducer

Reducer does what Reducer sounds like. It takes stuff in, reduces the number of stuff and returns less stuff. Pretty similar how government and taxes work.

Jokes aside, reducer will take 2 values and return 1 value. Give two, get one.

Imagine having an array of numbers and we want to add them all up. Reducer is a great tool for this need.

let numbers = [1, 2, 3]
const add = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0)
console.log(add) // 6

useReducer

useReducer can be used to manage complex state like Redux can. Unlike Redux, useReducer is build in and does not require any additional libraries or as I stated before you don't need to know Redux to learn/use useReducer.

Okay, that is cool, but how does it work?

When using useReducer, we define a reducer function that takes an action and returns a new state based on that action. The useReducer hook then returns an array with two values:

  • current state
  • dispatch function

Okay... what exactly is the dispatch function? It allows us to send actions to the reducer. Once we send an action, the state of the component is updated based on the action taken.

This is what syntax look like:

useReducer((CurrentState, actionToTake) => {
  return currentState + actionToTake
}, 0)
function counter() {
  const [add, dispatch] = React.useReducer((state, action) => {
    return state + action
  }, 0)
}

return (
  <>
    {add}

    <button onClick={() => dispatch(1)}>click to add one</button>
  </>
)

Clicking the button will increase the displayed value. onClick function will invoke the dispatch from [add, dispatch] part.

Let's take it step by step.

useReducer is setup with 2 parameters, state and action. The state is set to 0, you can see it at right below the return statement.

  • Before the click, state = 0,
  • "{add}" shows 0 on the screen
  • onClick={() => dispatch(1)} passes 1 to the dispatch
  • return state + action = return 0 + 1
  • component re-renders
  • "{add}" shows 1 on the screen