Nick Sweeting

@theSquashSH

Writing Shorter React-Redux Containers

If you write react + redux code all day, chances are your fingers are used to typing out this pattern of mapStateToProps, mapDispatchToProps, and connect:

As described in the redux docs: this pattern produces a “Container” which is a component that listens to changes in redux store and re-renders automatically.

It’s ok. The functions are re-usable, everything is straightforward, what’s not to like?

As an experiment, I wrote this, and ended up keeping it because it made the boilerplate more concise:

import {connect} from 'react-redux'
const reduxify = (container) =>
connect(
container.mapStateToProps,
container.mapDispatchToProps,
)(container.render)

All we’re doing is passing in mapStateToProps, mapDispatchToProps, and the render function together in one go instead of using a two-step chained function call.

Here’s the new, shorter syntax which uses the reduxify function to create a “Container”:

What was roughly ~9 lines of boilerplate turns into about~6 lines, but more importantly, it doesn’t reduce the nice qualities that the original had: testability & easy re-use of functions.

Testing & Re-use

Maybe you want to re-use mapStateToProps in more than one place, or you want to unit test it, not to worry!

They’re just functions, you can define them wherever you want, import them, and plop them into reduxify. Object property value shorthand allows it to stay clear and concise.

import {mapStateToProps} from './other-component.js'
const Component = reduxify({
mapStateToProps,
render: (props) =>
<div>...</div>
})

Here’s an example of mapStateToProps defined outside the reduxify call:

A helpful reader pointed out that mapDispatchToProps doesn’t even have to be a function if you use action creators:

Download the reduxify library

Haha just kidding, I’m not going to give you an npm package for a 6 line function, just copy/paste it :)

More by Nick Sweeting

Topics of interest

More Related Stories