afdsdsafadwer
afdsdsafadwer

Reputation: 67

Why we need pure reducer function in Redux

I am new to redux and studying this framework. As suggested in the document, it requires to return new state objects, instead of mutating the previous state. I just don't understand the purpose of this. JS arguments are call by value so changing arguments will not update the original value. Then what is the point of doing this?

Upvotes: 0

Views: 227

Answers (2)

Chang
Chang

Reputation: 1716

Great question. First of all, your understanding of the pass by value of JavaScript is not accurate. You could refer to this question about what exactly the underlying theory of this issue.

So the situation is that the item passed in is passed by value. But the item that is passed by value is itself a reference. Technically, this is called call-by-sharing.

That explained, another question is why should we maintain the previous states?

The answer is quite simple: Because we want the states to be trackable and more managable. And Redux is exactly the tool to help us manage that.

Imagine there is a stack of a few states, if you mutate the state itself, rather than making a copy and push it onto the top of the stack. You would find it hard to go back to the previous state. And it becomes less managable and vulnerable to large applications.

In Redux, every time we dispatch an action, we process it in an immutable way. That way, all the states are in perfectly control, and thus we could traverse through history. That's the zen of Redux IMO.

Hope that helps!

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074038

JS arguments are call by value so changing arguments will not update the original value.

Indeed, but if the value passed is an object reference (as it is with objects), and you use that object reference to change the state of the object, then it's not a pure function anymore.

For instance:

function notPure(obj) {
    // Modify object state
    ++obj.counter;
}

var o = {counter: 0};
notPure(o);
console.log(o.counter);

Instead, we'd be expected to return a new object with the modification:

function pure(obj) {
    return {counter: obj.counter + 1};
}

var o = {counter: 0};
var o2 = pure(o);
console.log(o.counter);
console.log(o2.counter);

Upvotes: 1

Related Questions