Pragmatic Redux: Connecting to React

There is a lot to like or dislike about Redux but let’s say the decision to use it has been made and now you need to understand Redux for professional reasons. This post is a good place to start because you first question is most likely how does my component get its data and react to changes in the data?

Redux connects to React by wrapping it – hype-word is higher-order component but, in the end, what you get after calling react-redux function connect is a React component placed inside another to enhance or encapsulate.

Redux data is provided as properties by the wrapper component. So called mapStateToProps, first function you pass to connect, decides which part of Redux store should be passed as properties to the wrapped component.

Changes to are detected by the wrapper component which listens to Redux store. When changes occurs, wrapper component re-renders the wrapped component. Concerns over irrelevant changes and redundant renders should be ignored in the beginning as React itself can soak up a lot of inefficiencies and Redux provides plumbings you can use to reduce unnecessary updates. There are limits, however, and it’s not that hard to run into them as your application grows.

At this point, two obvious and related questions arise which are:

  • How does the wrapper component discover Redux store?
  • How does the wrapped component dispatch actions?

Redux store is provided via context – use react-redux‘s Provider component to set that up. Wrapped component, however, don’t usually need direct access to Redux store as data is passed as properties and actions are dispatched via functions which are also passed as properties.

Use mapDispatchToProps, second function you pass to connect, to add functions that create and dispatch actions without having to declare contextTypes. It’s a minor yet useful feature.

Keeping Redux out of React is harder than it looks. To dispatch actions, component has to know about dispatching methods it received as props. If actions change, dispatching methods and reducers need to change. Changes to component, Redux state, actions or reducers will often require changes to others. It’s possible but the cost of creating reusable Redux connected React component is much higher than advertised in my opinion.