Redux connect()() is confusing. Why not use subscribe()?
Redux makes sense but when React comes into play with the react-redux
package you get confused.
First of all, the connect()()
-function has two sets of parameters. WTF?
And then you have the mapStateToProps
and mapDispatchToProps
function which are just complicated to write.
You think all just seems like unnecessary boilerplate code. Can’t you just use the subscribe()
function?
You get added performance when using connect
There are many reasons to use connect
- even though it seems a bit overcomplicated at first sight.
First of all, the connect function adds a bunch of optimizations to your app. Those optimizations make sure your component doesn’t render unnecessarily.
How does it optimize you ask?
The Redux store has a global state for your whole app. Your component doesn’t care about most of that stuff in the store but it just cares about a tiny part of it.
The connect function makes sure that your component only gets re-rendered if the relevant part of the store gets updated.
And you get a more clean code base
The second advantage of using connect() is that your React components get decoupled from Redux.
The mapStateToProps
function transforms the format of the state so that it suits your components. Your React component gets data on the format it needs via props. That way your component doesn’t have to know that Redux is being used. All the component see is data coming in as props. Read more about the mapStateToProps function here
When using connect()()
you are using a pattern called presentational/container component pattern. Your regular React components are the presentational components. And your component created with the connect function is the container component. Read more about the presentational/container pattern here
The double parenthesis ()() is there to empower you
And those double parenthesis do look very scary and weird at first. But once you know the secret of how they work, you will be happy they are there (or you will at least accept it :D ).
const VisibleTodoList = connect(mapStateToProps, mapDispatchToProps)(TodoList)
The first part looks familiar, it calls a function connect and passes in two variables. But then… another set of parenthesis? What does that even mean?
In JavaScript, a function can return another function. This is how the connect function is defined:
function connect(mapStateToProps, mapDispatchToProps) {
return function (component) {
// implementation
}
}
The reason connect is designed like this is that it’s possible to reuse connect for more than one components:
const connected = connect(mapStateToProps, mapDispatchToProps)
const VisibleTodoList = connected(TodoList)
const VisibleSomethingList = connected(SomethingList)
Are you curious to learn more about the implementation of connect? Check out this post: Code your own connect function