Global reducers with react-hooks

Jacob Ebey
2 min readNov 10, 2018

--

Playing with react-hooks this last week or so has been pretty great. It’s allowed me to drastically clean up form inputs with “useState”, changed how I interface with 3rd party libraries such as cytoscape.js with “useEffect”, and get this, has allowed me to do away with Redux with a combination of the two.

“But Jacob, react-hooks are not usable in a global context” you might say, and you are partly correct.

Before we get into the details, let’s take a quick look at how the pattern I’m going to introduce you to will be used.

I think that looks a lot prettier than using higher order components or a global Context / Provider.

The Deep Dive

Since we are operating on a global state, we are going to need to dispatch actions to multiple components when the state is mutated. To do this we are going to create a simple manager as follows:

With that in place, we can begin to create our “globalReducer” function. We know that we want to accept an initial state as well as an object with functions that mutate the state, and returns a function that allows us to use it in a react component, so let’s begin there:

The next step is to turn the reducer object we’ve been passed into a dispatch object that will be used by the consuming react components. The gist is that we reduce over the keys of the object and wrap the reducer methods in a dispatch method responsible for passing the current state to the reducer method and dispatching changes to consumers. This looks like the following:

Now that we’ve got the backbone in place, we can go ahead and introduce react-hooks. I’m going to just throw it all out there in a single code snippet as it’s really not much going on:

Wrap up

All in all, I think this is a pretty slick way to compose a global reducer. I’m looking forward to see how libraries like Redux/MobX improve/change their react implementations in the new and exciting world of react-hooks.

If you’d like to use some hooks such as “usePromise”, and a well maintained version of this article, you can find them at: https://github.com/jacob-ebey/react-hook-utils

--

--