Code with hooks and context

React Hooks and Context to Replace Redux

Things have changed since I came back to React a couple of weeks ago. I had used React extensively for 2 years around 2015-2017. Back then, redux was the craze. People wanted to use it for every project, no matter the complexity. React Hooks and Context have come to change that.

Now that I come back, it’s the other way around. Using Redux is seen as overkill now, nobody wants to go near it

I understand why, it brings a lot of boilerplate and it forces you into an architecture you might not be comfortable with.

So what are people doing to replace redux? React Hooks and Context. This lets everyone share globlal variables easily, which was the main selling point of Redux in my opinion.

Context

The context API was there before, yes, but it was cumbersome to use. React-Redux itself, alongside other libraries, used the old context API under the hood to share global variables. Things changed in React 16.3.

Context is easy to use now, and makes the data globally available anywhere in the component tree.

 If you need to update the context, then you can do that at the provider’s level, just pass in another user object. If you want to update the context from a nested component, you can pass a function through the context

Hooks

In the context code above, you may have seen this:

const { name } = useContext(UserContext)

That’s a hook. They are completely new to me, but they have quickly won my heart. If you’re not into them yet, just watch Dan Abramov introduce them:

When function components came around, I wanted to use them all over, they were nice and compact, and more javascript like (just functions).

I hated having to use class components just because I couldn’t handle state or lifecycle stuff in my function components. Now that hooks are here, there’s generally no reason not to use function components. Even the react team likes function components and want to get away from class components as you can see from the video

Do Hooks and Context replace Redux?

Not entirely. But they do provide you with what I think is Redux most important feature: Having global state easily available in any component. Like we saw before, if you have a context provider somewhere above your component’s tree, all you have to do in the component is

const { name } = useContext(UserContext)

and you can start using the user name in your component. But that’s pretty much all that Context gives us, Redux provides much more like handy dev tools, centralized app logic by using reducers, middleware to better handle async, powerful selectors to the state, and more. This stack overflow answer gives a nice and concise answer for React Hooks and Context vs Redux.

Example

Here’s a running example of the code used in this post. Try changing the name to yours!


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *