React declarative state updates

Learn how to use useReducer to write more declarative code

Aamir Saleem
2 min readApr 23, 2022
Photo by Ferenc Almasi on Unsplash

Let’s assume we are creating a custom fetch hook which we can use to fetch data from the API. For UX purposes, we’ll also need a few other pieces of state, loading and error.

Using useState, here’s one approach for how we’d accomplish this.

First, there is nothing wrong with this code. It just works fine. However, it’s a pretty imperative approach to solve the problem. Imperative approach focuses more on how we want to accomplish the task. Instead, what if we took a more declarative approach? Rather describing how we want to accomplish the task, let’s describe what we’re trying to accomplish. To accomplish this, we can utilize useReducer.

The reason useReducer can be more declarative is because it allows us to dispatch actions to change state and our reducer can contain the imperative, instructional code.

To see what this looks like let’s refactor our useFetch hook.

Notice that we’re describing what we want to do — fetch. Then, based on that result, success or error.

Here’s what all of the code now looks like, including our new fetchReducer.

If you liked the article, please clap to it and share it!

--

--