React with/without Redux

Global Reducer (hook) in React

As you probably know React.js provides us with these two helpful hooks — React.useReducer() and React.useContext(). You may think that combining them in a creative fashion would give you a perfect replacement for Redux? Not so fast :)

First, let’s see what’s the problem with Context-based implementation and how it may look like:

Can you quickly spot a problem with this approach? Whenever one of your components dispatches a new event, all the connected components, and their subtrees would re-render.

What you want to do instead, is making sure that a component using global state only re-renders if a change detected on a subset of data from the state that it requires.

Here is how a minimalistic solution may look like (src/reducer.js):

Where one component dispatches a global event, and the other one is subscribed to a subset of the global state reacting to the changes.

Note, that in a real-world project most likely you would be using Relay or something like that for global state management, and you would just need a small complementary tool that can be used for things like error messages, snackbar notifications etc.

Live demo https://codesandbox.io/s/react-global-reducer-v0rdn
See also React Starter Kit (serverless edition)

Happy coding!

Bringing the technical edge to early-stage companies with advice on software architecture, best practices, database design, web infrastructure, and DevOps.

Bringing the technical edge to early-stage companies with advice on software architecture, best practices, database design, web infrastructure, and DevOps.