A View On Redux

tl;dr I like using Redux as it helps me keep state changes simple. There are problems to be aware of with Redux but overall my experience with it has been overwhelmingly positive.

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.

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, 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”, 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.

Redux changed the way I think and improved the way I write React apps. I recommend giving it a go yourself.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.