The Benefits of Redux
What I like most about Redux is that I can use it to apply event sourcing to an entire React application's state.[0]This isn't unique to Redux at all. If you know of better alternatives, please let me know!
In this case, the events are actions and they are processed by reducers which update state. If all of the application's state is contained within Redux, then state can only change as a result of a reducer processing an action.
This is useful for me as I can think purely from the point of view of actions when I am thinking about state changes. I can reason about a series of actions and the resulting state. This reasoning transcribes neatly into test form, for example:
import myMathReducer from "./myMathReducer"
import {plus, times, minus} from "./myMathActions"
describe("my maths reducer", () => {
it("performs basic arithmetic on my number", () => {
const INITIAL_STATE = {myNumber: 5};
const actions = [plus(1), times(2), minus(3)];
const newState =
actions.reduce(myMathReducer, INITIAL_STATE);
expect(newState.myNumber).to.eql(9)
});
});
I find this great because:
- If the test makes sense to my pair[1]Does it makes sense to you? I'm hoping it is clear that we're asserting ((5 + 1) * 2) - 3 = 9, then I've gained confidence that I've got the state transitions clear in my head.
- The test acts as documentation on what actions are available and how they change the state.
- I've tested logic within my React app without having to go near mounting components and/or clicking buttons.
The Pitfalls of Redux
I've found Redux to be hard to use in anger at times. There are some nasty surprises which make for some very painful lessons.
The worst moment was bashing up against a bug for ages and finally finding out it was related to Redux blocking updates to components. This is when I learnt that the connect function has 3rd and 4th parameters you can pass to it. The fix was to mark my component as "impure"[2]The interesting implication here is that my code is not pious enough and the Redux Gods are smiting me for my heresy, via the 3rd parameter being passed to the connect function.
Luckily there aren't too many bumps along the road but they are quite noticeable. God forbid you ever accidentally give two actions the same type!
Redux is a big plus overall
I've found that, in the long term, using Redux has been massively helpful.
For me, the constraints imposed by Redux have helped me to keep things simple.[3]Lord knows I love the KISS principle
Redux changed the way I think and improved the way I write React apps. I recommend giving it a go yourself.