♻️ Reduce ♻️ Reduce ♻️ Reduce ♻️

In order to implement useReducer , first we need to create… a reducer of course! If you’re familiar with Redux, or the Flux architecture that it implements, this will be pretty straight forward. If you’re not, don’t worry, because this is still pretty straight forward and I’m going to walk through and explain everything as best I can. I won’t be diving into the pattern itself, but if you want to learn more, there’s already a ton of resources available. To get started, there are a couple of things to consider:

What we need to keep in our state How we want to structure our state

I chose the following, but feel free to modify this to conform with your needs.

// reducer.js

export const initialState = {

status: null,

response: null,

};

This structure allows us to easily get the status and response data of a request.

Now that we have our state data structure, we need to implement 3 actions.

Fetching — the action to dispatch when an api request is in progress Success — the action to dispatch when an api request completes successfully Error — the action to dispatch then an api requests result in error

I’ve separated my action types into a separate file, but you can include them in the reducer file if you like. Just make sure to export them so that you can use them whenever you need to reference an action type, such as in your action creators.

Action Types — prefixed with the name of the hook

Now we can use these types to create our reducer actions.

Reducer