DEV Community

Cover image for Next-Gen Way to Connect Redux Store to React Component
Tapajyoti Bose
Tapajyoti Bose

Posted on

Next-Gen Way to Connect Redux Store to React Component

Redux is one of the widely used State Management Solutions in React Applications. Even though it has several upsides, one major pain while working with Redux is the huge amount of boilerplate code you need to write to get it set up.

Adding to the pain is having to use connect function to map the state and dispatch to the React Component Props. This article will show you how to use data from the Redux Store in a better way using Hooks.

Old implementation

The old way implementation of connecting Redux Store to React Applications used connect from react-redux to add the selected parts of the store as component props:

const mapStateToProps = (state) => ({
    // select the parts of the state required, for example:
    // counter: state.counter.count
})

const mapDispatchToProps = (dispatch) => ({
    // create the required functions by dispatching actions, for example:
    // increment: () => dispatch(actions.increment())
})

export default connect(mapStateToProps, mapDispatchToProps)(Component)
Enter fullscreen mode Exit fullscreen mode

As you can see, that's a lot of code just to get the necessary data and functions. Let's now take a look at a more elegant solution.

Getting Redux Store Data

Getting Redux Store Data has been simplified several folds with the introduction of useSelector Hook. You can now use the hook to directly get the store data inside the React Component.

import { useSelector } from 'react-redux'

const Component = () => {
    const counter = useSelector((state) => state.counter.count)

    // ...
}

export default Component 
Enter fullscreen mode Exit fullscreen mode

Dispatching Actions

Just like useSelector hook, there is a hook for dispatch too. useDispatch gives you access to the Redux Dispatch function inside the React Component, allowing you to dispatch actions from anywhere inside the Component.

import { useDispatch } from 'react-redux'

const Component = () => {
    const dispatch = useDispatch()
    // For Example:
    // const increment = () => dispatch(actions.increment())
    // ...
}

export default Component 
Enter fullscreen mode Exit fullscreen mode

Comparison with connect

Hooks is obviously the future of React with React urging developers to use functional components over class components, but its important to compare the two because as per the use case, one approach might fair much better than the other.

Criteria Hooks connect
Developer Experience Incredibly Eases the Developer Experience. Hooks are really Intuitive, making them easier to read and write. A lot of additional code is required. Adds HOC (Higher Order Components), thus adding more components to the component tree (can be seen in React Dev Tools)
Stability Might lead to some (rare and avoidable edge cases) weird edge cases with useSelector, such as Stale Props and Zombie Children. For details click here connect is way more mature than these hooks and has already worked out these in the older versions of connect, leading it to be a bit more stable
Performance useSelector accepts a second argument - an equality function to determine if the state has changed connect has some advanced techniques, using merge props and other options hidden in the connect function.
TypeScript Using Hooks with TypeScript is a breeze and can be done without much hassle Using connect with TypeScript is a nightmare, often requiring you create multiple interfaces for similar, but slightly different items
Testing Testing Components with these Hooks is tad more difficult Testing the Component Props (added by connect) is quite easy

As you can see both methods have their merits and demerits. It is better to use the method that works better in your use case

NOTE: You still need to set up the Redux boilerplate the get the hooks working with React to give you access to the store using the Hooks. This method only reduces the extra code for the connection logic.

Wrapping up

In this article, we went over an alternate approach to connecting Redux Store to React Components. We also discussed the merits and demerits of this new approach and how it can help developers. Hope this helped you in your React Development Journey! :)

Thumbs Up

Thanks for reading

Want to work together? Contact me on Upwork

Want to see what I am working on? Check out my GitHub

I am a freelancer who will start off as a Digital Nomad in mid-2022. Want to catch the journey? Follow me on Instagram

Follow my blogs for weekly new tidbits on Dev

FAQ

These are a few commonly asked questions I get. So, I hope this FAQ section solves your issues.

  1. I am a beginner, how should I learn Front-End Web Dev?
    Look into the following articles:

    1. Front End Development Roadmap
    2. Front End Project Ideas
  2. Would you mentor me?

    Sorry, I am already under a lot of workload and would not have the time to mentor anyone.

  3. Would you like to collaborate on our site?

    As mentioned in the previous question, I am in a time crunch, so I would have to pass on such opportunities.

Connect to me on

Discussion (15)

Collapse
raibtoffoletto profile image
Raí B. Toffoletto

How about redux-toolkit?

Collapse
volubleogre664 profile image
volubleogre664

I was here to mention Redux-toolkit
It further simplifies everything and the boilerplate code you write is very small and simple
I actually have a custom hook that does exactly what's in this article but in a much more simple way and it is using redux-toolkit

Collapse
raibtoffoletto profile image
Raí B. Toffoletto

It also greatly improves async data fetching when you aren't using something like react-query. It provides useSelect and useDispatch as hooks, making things very easy, maybe the async set up could be improved, but after you understand its mechanics it makes sense. Start by their guides on the official website, I guarantee you will like it 😁

Collapse
ruppysuppy profile image
Tapajyoti Bose Author

Could you please share it? It would help out the readers a lot

Collapse
ruppysuppy profile image
Tapajyoti Bose Author

Yes, a lot of people had been using it lately. I haven't used it yet, so I don't have enough experience to comment on it

Collapse
krtirtho profile image
KR Tirtho

So the next-gen react-redux is actually zustand? Didn't expect they'd copy the API of it but that's the fun part of open-source. But at least it'd take fewer boilerplates

Collapse
ruppysuppy profile image
Tapajyoti Bose Author

Its quite similar, yet different from zustand.

Ps: I don't know much about zustand, I looked through how it's used and drawing conclusion from that

Collapse
krtirtho profile image
KR Tirtho

Of course, they don't work similarly
zustand is much more flexible, simple & atomic. FYI, it doesn't have the zombie-child/stale-props issue too
It's a great state manager for simplicity in your codebase

Thread Thread
ruppysuppy profile image
Tapajyoti Bose Author

Great! I'll definitely look into it

Collapse
phryneas profile image
Lenz Weber • Edited

This is pretty much as old as Zustand - it came out 2019, a few months after React hooks came out (after some fiddling they did to make sure that the api was good)

Collapse
boberbober profile image
Gregory Bober

Just use Recoil. I was a long time Redux user and then tried Recoil and I'm never going back. Recoil feels like it's part of React. Redux always needed so much unnecessary adapters, selectors, etc.. Recoil is fantastic.

Collapse
wobsoriano profile image
Robert

The recommended way is to use RTK. It's even in the docs.

Collapse
victorhqc profile image
Victor Quiroz

Was the performance difference actually tested? I don't think it has a signifficant difference using hooks or connect(). Of course, I can be wrong, and that's why having some results that prove this claim would be nice to see.

Collapse
ruppysuppy profile image
Tapajyoti Bose Author

I haven't tested it. I read some that the performance for both the approaches are at par with each other, but you can optimize the performance of connect a bit more than the optimization for the hooks

Collapse
tronin profile image
Tronin Denis

If you would like to have long term support for your React application use pure redux with redux-saga for managing side effects.