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

renders You remove a feed from the list the ENTIRE <Page> renders

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

renders Removing a feed from the list only <Feed> renders

renders Adding an image only <Images> renders

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