Reputation: 2138
Two functions to change reducer state:
function1 (state, newValue) {
const newValue1 = newValue + 1;
const newValue2 = newValue * 7;
return {...state, newValue2}
}
function2 (state, newValue) {
let newValue1 = newValue + 1;
newValue1 = newValue1 * 7;
return {...state, newValue1}
}
Which one is correct? Does only state has to be immutable or any variable?
Upvotes: 0
Views: 118
Reputation: 4094
Both are correct. As you've said, only the state has to be immutable. In your case, simply don't mutate the state
variable in any way.
Upvotes: 1
Reputation: 5840
The idea behind an immutable state object is just that you don't change state
directly. So doing this would be wrong:
let state = {...}
function changeState(newValue) {
state.newValue = newValue
}
I don't know the rest of your code to say it's right or wrong, but in the examples you provided, you are not mutating state - you're returning a new object that takes everything from the existing state as-is (destructuring state with ...state
) and adding or overriding newValue
in the newly returned object.
As to whether or not it's wrong to change newValue
(or other variables), again both of your instances are fine. It's perfectly find to use, change, and run logic in your reducers to ultimately come up with a new object (or whatever) for the updated state.
Upvotes: 0