React hooks like am 5-ish : useReducer

React hooks like am 5-ish : useReducer

A brief dive into the useReducer hook

useReducer

useReducer according to the docs

useReducer is defined in the official docs as an alternative to useState, if you have heard of Redux, yes, it works just like Redux, so if you have always used redux, useReducer shouldn't be very different. If you have no idea what redux is, don’t worry, by understanding how useReducer works, you should be able to transfer your knowledge when you get into redux.

useReducer is usually recommended for when you have complex state logic to work around.

Usually, when I have more than 3 useState instances that's when I begin to think of useReducer. Also when you pair useReducer with useContext, you can implement a lot of complex functionality that you might have needed an external state management tool for.

In this article, I try to break down this useful API so it's easier to understand and use...

Understanding useReducer

To understand the useReducer hook, let's first take a look at what a reducer function is in JS.

A reducer function is a simple function that accepts two arguments and returns a new state value, based on the arguments.

// a reducer function in its basic form

(state, action) => newState

// a more advanced implementation
 const colorReducer = (color, action) => {
     switch(action.type) {
        case 'danger':
            return 'red'
        case 'success':
            return 'green'
        default:
            return 'blue'
    }
}

In the above code snippet, we define what a reducer function should look like and proceed to walk through a more realistic example.

Assuming that our app, requires that we return a certain color given a certain condition, this code should be fine. However, in Reactland, things are going to get a little bit more detailed since our apps are not going to require just a color value.

The above example also means that we can have several reducers for different things as we see fit for our app.

When to use useReducer

  • In simple terms, use useReducer when the logic you are to implement is going to be really complex, like a cart functionality with many moving parts, from knowing what items are in the cart object to calculating the total cost to removing and adding to the cart, I hope you get the picture, that’s complexity right there.

Reference articles for further reading...