Using react, we are told to never modify this.state
directly and treat it as immutable. Which makes sense. But consider this situation:
export default class Example extends Component {
constructor() {
super();
this.state = {
largeArray = [values, in, here],
}
}
copyAndAddElement = () => {
const newState = [ ...this.state.largeArray ];
newState.push({ something: 'new' });
this.setState({ largeArray: newState });
}
mutateAndSet = () => {
this.state.largeArray.push({ something: 'new' });
this.setState({ largeArray: this.state.largeArray });
}
render = () => ( JSON.stringify(this.state.largeArray) )
}
Maybe I'm just being naive, but why not just use mutateAndSet
? If you have a lot of data in that array, isn't it process intensive to do a deep copy in order to modify it?
The only problem that I see could be with the asynchronous nature of setState
, being that largeArray
could be modified by a different function before the setState
in muateAndSet
actually executes. In my case I'm just adding points to a graph, never removing or modifying from another place.
If I have a very large array, why should I not take the seemingly more performant route?