How to update nested states in React, should state be immutable? - javascript

We are having a heated discussion on how to update nested state in React.
Should the state be immutable or not? What is the best practice to update the state gracefully?
Say you have state structure that looks like this:
this.state = {
numberOfStudents: "3",
gradeLevel: "5",
students : [
{ id : "1234",
firstName: "John",
lastName: "Doe",
email: "johndoe#mail.com"
phoneNumer: "12345"
},
{ id : "56789",
firstName: "Jane",
lastName: "Doe",
email: "janedoe#mail.com"
phoneNumer: "56789"
},
{ id : "11111",
firstName: "Joe",
lastName: "Doe",
email: "joedoe#mail.com"
phoneNumer: "11111"
}
]
}
Then we want to update joe doe's phone number.
A couple of ways we can do it:
mutate state + force update to rerender
this.state.students[2].phoneNumber = "9999999";
this.forceUpdate();
mutate state + setState with mutated state
this.state.students[2].phoneNumber = "9999999";
this.setState({
students: this.state.students
});
Object.assign, this still mutate the state since newStudents is just a new reference to the same object this.state points to
const newStudents = Object.assign({}, this.state.students);
newStudents[2].phoneNumber = "9999999"
this.setState({
students: newStudents
});
Update immutability helper (https://facebook.github.io/react/docs/update.html) + setState. This can get ugly very quickly if we have address.street, address.city, address.zip in each student object and want to update the street.
const newStudents = React.addons.update(this.state.students, {2: {phoneNumber: {$set:"9999999"}}});
this.setState({
students: newStudents
})
Last line of the react doc for setState states that :
Never mutate this.state directly, as calling setState() afterwards may
replace the mutation you made. Treat this.state as if it were
immutable.
https://facebook.github.io/react/docs/react-component.html
The docs states that we shouldn't use forceUpdate to rerender:
Normally you should try to avoid all uses of forceUpdate() and only
read from this.props and this.state in render().
Why is this the case, what can happen if we mutate state and call setState afterward? Under what circumstances will setState() replace the mutation we made? This is a very confusing statement. Can someone please explain the possible complication of each of the scenario we are using above to set the state.

You state that:
"Object.assign, this still mutate the state since newStudents is just a new reference to the same object this.state points to"
This statement is incorrect.Object.assign mutates the state passed in to its first parameter. Since you pass in an empty object literal ({}), you are mutating the new object literal and not this.state.
Some background:
The principle of Immutable state has connections with Functional programming.
It is useful in React because it provides a way for React to know if
the state has changed at all, one use case it is useful is for optimising when components should re-render
Consider the case of a complex state with nested objects.
Mutating the state's values would alter the values of properties within the state but it would not change the object's reference.
this.state = {nestObject:{nestedObj:{nestObj:'yes'}}};
// mutate state
this.state.nestObject.nestedObj.nestObj= 'no';
How do we know if React should re-render the component?
A deep equality check? Imagine what this would look like in a complex state, that's hundreds, even thousands of checks per state update...
No need to check for changes, just force React to re-render everything with every state change...
Could there be an alternative to the latter two approaches?
The Immutable way
By creating a new object (and therefore a new reference), copying over the old state with Object.assign and mutating it, you get to manipulate the state values and change the object reference.
With the Immutable state approach we can then know if the state has changed by simply checking if the object references are equal.
An simplified example for the naysayers in the comments below:
Consider this simple example:
this this.state = { someValue: 'test'}
var newState = Object.assign({}, this.state);
console.log(newState); // logs: Object {someValue: "test"]
console.log(this.state); // logs: Object {someValue: "test"]
// logs suggest the object are equal (in property and property value at least...
console.log(this.state === this.state); // logs: true
console.log(this.state === newState); // logs: false. Objects are
// pass-by-reference, the values stored
// stored in this.state AND newState
// are references. The strict equality
// shows that these references
// DON'T MATCH so we can see
// that an intent to modify
// state has been made

Related

Why use the spread operator when calling 'setState()' in React?

I just start picking up react.js so I went through a lot of tutorials and I've stumbled upon this bit which basically meant to delete an item from the state.
this is how the guy introduced to me the delete function
delTodo = id => {
this.setState({
todos: [...this.state.todos.filter(todo => todo.id !== id)]
});
};
Since I am not so familiar with javascript I had a hard time figuring out what the ... operator is doing and why exactly is he using it in the given scenario. So in order to have a better understanding of how it works, I played a bit in the console and I've realised that array = [...array]. But is that true?
Is this bit doing the same exact thing as the one from above?
delTodo = id => {
this.setState({
todos: this.state.todos.filter(todo => todo.id !== id)
});
};
Could someone more experienced clarify to me why he has chosen to be using that approach instead of the one I've come up with?
As per the documentation:
Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
reactjs.org/docs/react-component.html#state
So, in the example from the tutorial you've mentioned, you wouldn't need to make a copy of the array to update your state.
// GOOD
delTodo = id => {
this.setState({
todos: this.state.todos.filter(...)
})
}
Array.filter method creates a new array and does not mutate the original array, therefore it won't directly mutate your state. Same thing applies to methods such as Array.map or Array.concat.
If your state is an array and you're applying methods that are mutable, you should copy your array.
See more to figure out which Array methods are mutable:
doesitmutate.xyz
However, if you were to do something like the following:
// BAD
delTodo = id => {
const todos = this.state.todos
todos.splice(id, 1)
this.setState({ todos: todos })
}
Then you'd be mutating your state directly, because Array.splice changes the content of an existing array, rather than returning a new array after deleting the specific item. Therefore, you should copy your array with the spread operator.
// GOOD
delTodo = id => {
const todos = [...this.state.todos]
todos.splice(id, 1)
this.setState({ todos: todos })
}
Similarly with objects, you should apply the same technique.
// BAD
updateFoo = () => {
const foo = this.state.foo // `foo` is an object {}
foo.bar = "HelloWorld"
this.setState({ foo: foo })
}
The above directly mutates your state, so you should make a copy and then update your state.
// GOOD
updateFoo = () => {
const foo = {...this.state.foo} // `foo` is an object {}
foo.bar = "HelloWorld"
this.setState({ foo: foo })
}
Hope this helps.
Why use the spread operator at all?
The spread operator ... is often used for creating shallow copies of arrays or objects. This is especially useful when you aim to avoid mutating values, which is encouraged for different reasons. TLDR; Code with immutable values is much easier to reason about. Long answer here.
Why is the spread operator used so commonly in react?
In react, it is strongly recommended to avoid mutation of this.state and instead call this.setState(newState). Mutating state directly will not trigger a re-render, and may lead to poor UX, unexpected behavior, or even bugs. This is because it may cause the internal state to differ from the state that is being rendered.
To avoid manipulating values, it has become common practice to use the spread operator to create derivatives of objects (or arrays), without mutating the original:
// current state
let initialState = {
user: "Bastian",
activeTodo: "do nothing",
todos: ["do nothing"]
}
function addNewTodo(newTodo) {
// - first spread state, to copy over the current state and avoid mutation
// - then set the fields you wish to modify
this.setState({
...this.state,
activeTodo: newTodo,
todos: [...this.state.todos, newTodo]
})
}
// updating state like this...
addNewTodo("go for a run")
// results in the initial state to be replaced by this:
let updatedState = {
user: "Bastian",
activeTodo: "go for a run",
todos: ["do nothing", "go for a run"]
}
Why is the spread operator used in the example?
Probably to avoid accidental state mutation. While Array.filter() does not mutate the original array and is safe to use on react state, there are several other methods which do mutate the original array, and should not be used on state. For example: .push(), .pop(),.splice(). By spreading the array before calling an operation on it, you ensure that you are not mutating state. That being said, I believe the author made a typo and instead was going for this:
delTodo = id => {
this.setState({
todos: [...this.state.todos].filter(todo => todo.id !== id)
});
};
If you have a need to use one of the mutating functions, you can choose to use them with spread in the following manner, to avoid mutating state and potentially causing bugs in your application:
// here we mutate the copied array, before we set it as the new state
// note that we spread BEFORE using an array method
this.setState({
todos: [...this.state.todos].push("new todo")
});
// in this case, you can also avoid mutation alltogether:
this.setState({
todos: [...this.state.todos, "new todo"]
});
As .filter gives you a new array (than mutating the source array), it is acceptable and results in the same behaviour, making spreading redundant here.
What's not acceptable is:
const delIndex = this.state.todos.findIndex(todo => todo.id !== id);
this.state.todos.splice(delIndex, 1); // state mutation
this.setState({
todos: this.state.todos
});
slice is fine though:
const delIndex = this.state.todos.findIndex(todo => todo.id !== id);
this.setState({
todos: [
...this.state.todos.slice(0, delIndex),
...this.state.todos.slice(delIndex + 1)
]
});
If you mutate state (which keeps ref same) React may not be able to ascertain which part of your state actually changed and probably construct a tree on next render which is different from expected.
The spread operator that the guy's code is applying causes the array returned from the filter function to be copied again.
Since [.filter is returning a new array][https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter], you will already avoid mutating the array in state directly. It seems like the spread operator may be redundant.
One thing I wanted to point out too is while the values in a copied array may be the same as the values in an old array (array = [...array]), the instances change so you wouldn't be able to use '===' or '==' to check for strict equivalency.
const a = ['a', 'b']
const b = [...a]
console.log(a === b) // false
console.log(a == b) // false
console.log(a[0] === b[0]) // true
console.log(a[1] === b[1]) // true
Hope this helps!

React Array in State Mutating

I don't know if there is a conflict in the libraries I'm using but for some reason or its, the latest react but when I'm updating an array from the state, it's mutating it even though I haven't called setState. Is there a special case for Arrays in the state that I'm not aware of?
constructor(props){
super(props);
this.state = {
data: [
{ id: 1, name: 'hello' },
{ id: 2, name: 'world' },
{ id: 3, name: 'once' }
]
}
}
performUpdate() {
const { data } = this.state;
var current_data = data.slice();
current_data[0].name = 'helloooooo';
console.log(data)
// it shows data.id 1 now has name: 'helloooooo'
}
Since I made a copy of the array from state, shouldn't the state be updated only if I call
this.setState({
data: current_data
})
Since I made a copy of the array from state, shouldn't the state be
updated only if I call
You made a shallow copy. This:
current_data[0].name
is same as saying:
this.state.data[0].name
this.state.data[0] and current_data[0] point to same object, due to shallow copy; even though slice returned new array, its elements basically point to same objects as the elements from the original array.
You maybe interested in how to immutably modify one of array elements.
slice performs a shallow copy of the array - meaning that only the pointers to the objects contained in the array are copied, not the objects themselves.
This means that after the slice you have two arrays pointing at the same objects. Naturally, then, changing an object in one, will change it in the other.
Instead, what you want to do is create a deep clone. You can use immutability-helper or something like Lodash to achieve this.

the spread operator in Redux reducer

I am trying to understand what does spread operator do in Redux state?
I went through this question Purpose of the Spread syntax in React-Redux Reducers but wasn't convince with Answer for some reason.
Can someone please explain me in very simple terms why do we do something like this
case WHATEVER:
return {
...state,
DateSucess: action.payload,
Instead of just
case WHATEVER
return {
DataSucess: action.payload
The spread operator does the same as in ES6, is still the same behaviour (check the MDN docs).
About the motivation to use the ...state the idea is simple: Keep the old state and add or overwrite the DateSucess property.
So let's say:
const state = {foo: 'bar', DateSucess: 'oldDateSuccess', zip: 'zap'}
If you don't use spread the new value of state would be only DateSucess and you would lose the foo and zip value, using spread you are just overwriting DateSucess keeping the rest of the value untouched.
This spread would be equivalent to the following with Object.assign
return Object.assign(oldState, {DateSucess: 'newDateSucess'})
Spread operator simply return copy of array or obj associated with is. Look into example below
const abc = {
'first_key':1,
'second_key':2,
}
const newObj={...abc} //will COPY abc
const newObjWithNewKey = {...abc, 'first_key':'01 first','new_key':'007'} // will COPY abc and value of first_key will be replaces with new value as it exists. will add new keyvalue pair new_key.
console.log("abc",abc,"newObj",newObj,"newObjWithNewKey",newObjWithNewKey)
Now in redux if you just return new payload then you will lose other state values.
but if you use ... means you tell js that copy existing state and update values of specified keys if there is no key then add new one
Assume that your state structure looks like this:
const initialState = {
DateSucess: ' ',
DateFailure: ' '
}
Well then, with that state, now we write a reducer and..
The reducer is a pure function that takes the previous state and an
action, and returns the next state.
In the reducer, we make some calculation and return the next state. Keeping in mind that, we don't mutate the state. We create a copy with Object.assign().
Object.assign(state, { DateSucess: action.payload}) is also wrong: it will mutate the first argument. You must supply an empty object as the first parameter. Like this:
return Object.assign({}, state, { DateSucess: action.payload})
You can also enable the object spread operator proposal to write { ...state, ...newState } instead. In your case, it will look like:
return {...state, DateSucess: action.payload}
For more information: https://redux.js.org/basics/reducers
If you are using react and asking about react-redux, here might be the answer for you-
We shouldn't mutate a state inside the reducers. With spread operator, we make a copy of the previous state and update the copy of it. So that, we aren't mutating our prev state and at the same time, updating it. This is the function of spread operator.
Now, another question may arise. Why we can't mutate in reducers. Well that's a 'react' thing to me. React creates virtual dom for handling manipulations of doms. If you alter the internal state, the sync of dom and virtual dom may break and things will go bad.
Hope this description helps you.

If redux updates a nested component but a PureComponent is passed it's parent as a prop, will the PureComponent rerender?

In redux if your action/reducer updates the value of foo.bar and your connected component's mapStateToPropsis (store) => { foo: store.foo } and then passes foo={foo} to a PureComponent child. The child won't rerender when foo.bar changes? That's why they recommend keeping things as flat as possible?
Thanks for the clarification.
There are two questions:
Generally, when does a PureComponent instance update?
Is the PureComponent component instance updating in this example?
Question #1: PureComponent does a shallow comparison of props in shouldComponentUpdate. What this means is described well in the answer to this question. To summarize, a shallow comparison checks for equality of reference rather than equality of value. So, if lastProps.myObj and nextProps.myObj are both references to the same object, a shallow comparison evaluates to true even if lastProps.myObj.foo and nextProps.myObj.foo are not equal.
Question #2: If you have mutated state.foo, so that it's the same object with a changed value, then a shallow comparison will return a false negative. The complicating factor here is that your example uses Redux. You say that a Redux reducer has changed state.foo. One of the first rules of Redux reducers is that they don't mutate state or props. They return a new state. When state is an object, they make a copy of the object and apply the change to the copy. If you are honoring the reducer contract and updating the state without mutating it, then you have changed the reference. In that case, the PureComponent.prototype.shouldComponentUpdate should return true.
// create an object
var foo = {bar: 'bar'};
// make a copy of the object
var bar = Object.assign({}, foo);
// both objects look the same, i.e. have the same property with an equal value
foo.bar === bar.bar // -> true
// but they are not the same object so the shallow comparison evaluates to false
foo === bar // -> false
So if the PureComponent instance is not updating when state.foo has changed, I would review the reducer that changes foo and make sure the update is not a mutation.

ReactJS - push json into state array

I'm simply trying to append a json created dynamically into an array that lives inside the state.
The only way that I've found till now is to use concat, because push doesn't work.
constructor() {
super()
this.state = {
list: []
}
this.add = this.add.bind(this)
}
add(e) {
e.preventDefault()
var task = document.getElementById('task').value
var json = JSON.parse(JSON.stringify({key: task, item: task}))
this.setState({list: this.state.list.concat(json)}) // WORKS
// this.setState({list: this.state.list.push(json)}) // DOESN'T WORK
console.log(this.state.list)
document.getElementById('task').value = ''
}
That works, but I don't understand why I have an empty array in console after the first item it's created. I've read how concat works, but obviously I missed something. Why I can't push an object inside my this.list array?
The concat otherwise create a new array and return it.
The push returns the new length of the array, which means a number, which means NOT what you want to set to state.list. That's why it didn't work.
why I have an empty array in console
From the docs: setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. That's why you are getting the empty array in the console.
And one more thing, don't mutate your state directly. If you call state.list.push(...), your changes will not be maintained by React and will be discarded if you call setState later. So it's a good thing to use concat.
this.state is immutable and has to be changed only via the setState() function.
From the docs:
NEVER mutate this.state directly, as calling setState() afterwards may
replace the mutation you made. Treat this.state as if it were
immutable. setState() does not immediately mutate this.state but
creates a pending state transition. Accessing this.state after calling
this method can potentially return the existing value.
So, the best way to do this is to replace the array in this.state by a new array, and not try to push/modify it.
var newState = Object.assign({}, this.state); // Clone the state obj in newState
newState[arrayKey].push(newItem); // modify newState
this.setState(newState); // setState()
Array.prototype.push() returns the new length property of the object upon which the method was called.
See:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push#Returns

Categories