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
- You remove a feed from the list the ENTIRE
- You add an image the ENTIRE
Instead of connecting to the
<Page> component let’s connect
<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
- Removing a feed from the list only
- Adding an image only
- 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.
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.
- 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.
- Good ol’ RTFM — read the react-redux docs in full. It turns out that the
connectmethod has plenty of options beyond passing
mapDispatchToProps, including a
renderCountPropyou can add to your component to track render count.