javascriptreduxpure-function

Why are pure reducers so important in redux?


Pure reducers have no side effects and enable things like time-travelling. They make reasoning about application behavior easier.

This is intuitive to me. But I cannot articulate WHY pure reducers lead to these positive non-functional attributes.

Can someone help me articulate why making reducers side-effect free makes reasoning about application behavior easier?

Is it because you are guaranteed to have the exact same state after running the reducers?

If so, surely even side-effectful (ie. non-pure) reducers could have this property?


Solution

  • Is it because you are guaranteed to have the exact same state after running the reducers?

    Yes, pure reducers are deterministic, meaning that if they are given the same input, they will always produce the same result output. This property helps with situations like unit testing, because you know if a test passes once, it will always pass.

    If so, surely even side-effectful (ie. non-pure) reducers could have this property?

    No, impure reducers would rely on both the inputs and on the state of the application. They could behave a given way 1000 times while you're testing, but break when your application happens to be in a particular state that you never thought to test.

    Of course, it's perfectly possible to have a gap in your unit testing that misses a corner case. But if the test's results are 100% based on the inputs then you're far more likely to notice those corner cases just by looking at the stated inputs expected by the reducer.

    If a function changes the application's state, then running the same function twice, or the same few functions in different orders, may cause completely different behavior. This makes it hard to reason about the correctness of the application because in order to know whether a given line of code is correct, you have to know what happened prior to calling it, possibly in a completely different part of the application.