React-Redux 7.1 brings hooks.

June 12, 2019

The way grownups handle state in larger React apps is with Redux, and the only way to use it from React is by using the React-Redux package. Instead of the state being a part of your components it becomes a seperate thing, this has many advantages like seperatation of cencerns, easier to make re-usable code etc. The way it works is that you set up your redux stuff with reducers, actions, action creators etc, create a store and add that as near the root of your react app as possible. Then you used to use the connect function to inject state and actions into your compoenets.

Connect is great, you can do a lot with very little code, but it is a little bit hard to explain to new people, and it can be a real pain in the ass to debug. The way most people use it is that you give it two callbacks one for selecting data from state and a second one for wrapping your your action creators in dispatch, and then you pass your component as the argument to the second function. It usually looks something like this: connect(({value1, value2}) => ({value1, value2}), dispatch => ({someAction: (input) => dispatch(someAction(input))})(Component).

It isn’t great, but the best we have had, and you can make it a lot better with some functions that make the job of mapping dispatch more automatic and having selector functions that select state etc.

The new hooks introduced in react-redux make this a lot better though. With this you can make proper container functions that are declarative. You can use useSelector to select values from the store, and useDispatch + useCallback to create wrapped actionCreators. I have not used it yet, but I do think it looks very promising. And I’m always a sucker for more declarative code.