The React setState API for Redux
Redux boilerplate can be verbose. This is how to still use Redux and only write a little more code than when using React setState.
React setState is simple. Use it to update the component state and the component re-renders to reflect the changes. Simple, predictable, perfect.
In react-redux mapDispatchToProps (combined with initial state, reducers, and actions) can be somewhat more complicated. It’s definitely a lot more boilerplate. And frameworks like reason-react for ReasonML, Yew in the Rust language, and Elm of old… just seem to be taking this verbose reducer architecture all too seriously.
This is how I dispatch my actions:
this.props.setProps({count: this.props.count + 1})This is how I decouple my functions into slightly more testable pieces:
<div onClick={divOnClick(this.props.setProps)} />But it’s just a little more complicated
The mapStateToProps in react-redux is awesome. It’s only mapDispatchToProps that I have a small beef with.
This is how I mapDispatchToProps (I don’t):
export default connect((store: IStore) => {
return {
count: store.reducer.count
};
})(
class Counter extends React.Component {
// ...
}
);Notice there’s only mapStateToProps? I wrapped connect with my own version to make sure I don’t need mapDispatchToProps.
This is the one shared file I use in my several React SPA apps:
It’s a lot, but I’ll break down some pieces.
I wrapped Redux connect
Two things:
- The
react-reduxmapStateToProps is so awesome and I didn’t change it. - My one (and only) action, setProps, works almost identically to setState (I imported Ramda as R).
I wrote my own provider
I didn’t want to create the Redux store boilerplate everytime I start a new project:
It’s used like this:
const Provided = provide(
{
count: 0
},
class CounterApp extends React.Component {
public render() {
// ...
}
}
);Notice I set an initial state of zero for the count?
What I’m leaving out
The one big file I shared handles history, URL-parameters, and page hash. Maybe react-router or some other library works great for this, but I’ve had past reasons not to buy into them.
I plan on doing a lot of armchair philosophizing about all the tools I can’t use yet because they don’t exist, so I thought it might be healthy to take a small thing and use some code snippets to make a simple point too.
