Ryan Johnson
DailyJS
Published in
3 min readApr 24, 2017

--

Want to learn React? Check out my new course React for Beginners: Build and app, and learn the fundamentals.

Quick Redux tips for connecting your React components

If you’re using Redux in your React app you’re likely using react-redux to connect your components to your state. The connect method is a tricky sum bitch— although it has a very simple API there’s a lot of magic happening under the hood. It’s very easy, especially when first learning Redux, to just start connecting things without much thought on what’s actually happening. One of the easiest snafus to make is to connect your component at the top of the render tree.

What the hell does that mean exactly? I’m glad you asked — the following diagram demonstrates this scenario. In this example the <Page> component is connected at the top of the render tree.

Why does this suck?

  • You change the profile image the ENTIRE <Page> renders
  • You remove a feed from the list the ENTIRE <Page> renders
  • You add an image the ENTIRE <Page> renders

Instead of connecting to the <Page> component let’s connect <Profile>, <Feed>, and <Images> directly to their slice of state. Here’s an updated version of the same diagram to demonstrate:

Why is this better?

  • Changing the profile image only <Profile> renders
  • Removing a feed from the list only <Feed> renders
  • Adding an image only <Images> renders
  • Less renders === 🌈🌈🦄🦄

Remember when you connect your component you are telling React to render the component anytime any of the connected props changes. By having each component do it’s own connect we avoid the unnecessary renders that were happening when we connected at the top of the render tree.

Wrapping up

I recommend anyone new to connect takes the time to fully understand what is going on when you connect a Component. I myself was guilty of doing cut & paste from tutorials at the beginning, and taking many missteps along the way.

Bonus Round

  1. If you are doing Redux I recommend taking a look at reselect. This allows you to create smart getters for Redux called selectors. A selector is not recomputed unless one of its arguments change, which will help avoid unnecessary renders.
  2. Good ol’ RTFM — read the react-redux docs in full. It turns out that the connect method has plenty of options beyond passing mapStateToProps and mapDispatchToProps, including a renderCountProp you can add to your component to track render count.

For more React, Redux, and JavaScript reading follow me on Medium or Twitter.

--

--

Ryan Johnson
DailyJS

fullstack web developer • JavaScript • React.js • AngularJS • Node.js