5

I have been told that whenever I am working with react state or changing it, I should make a clone or copy of it.

const cloneState = [...this.state]
cloneState.name = 'hardik'

But I am not sure why people recommend it, Why can't i directy change state?

why shouldn't I just do it using it

this.setState({name: 'hardik'})
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Alwaysblue
  • 9,948
  • 38
  • 121
  • 210
  • In your example, you can definitely use `this.setState({name: 'hardik'})` as [React class components' `setState` do a shallow merge automatically.](https://reactjs.org/docs/react-component.html#setstate) – Emile Bergeron Jul 23 '20 at 20:56
  • 1
    Does this answer your question? [Why can't I directly modify a component's state, really?](https://stackoverflow.com/questions/37755997/why-cant-i-directly-modify-a-components-state-really) – Emile Bergeron Jul 23 '20 at 20:56

2 Answers2

2

React determines whether or not to re-render a component based on whether the state has changed.

It determines whether or not the state has changed by testing its referential equality.

This means that it'll check if this.state === this.state

If you mutate a piece of state, say by doing: cloneState.name = "hardik" the states will be referentially equal since it was a mutation.

When you "clone" the state by creating a new object [...this.state] === this.state is false which triggers a re-render.

Spencer Bard
  • 1,015
  • 6
  • 10
  • Can you please explain this line `referentially equal since it was a mutation` – Alwaysblue Jul 23 '20 at 20:04
  • 1
    Sorry! Referential equality is checking whether or not `objectA` is the same object as `objectB`. So if you have some code `const objectA = {name: "myname"}` and `const objectB = {name: "myname"}` though those objects contain the same info they are not the same object so `objectA === objectB` is false meaning they are not referentially equal because they do not refer to the same object. However if you have `const objectA = {name: "myname"}` and `const objectB = objectA` then `objectA === objectB` is true and `objectA === objectB` is true even after doing something like `objectA.name = "oops"` – Spencer Bard Jul 23 '20 at 20:07
-1

best use the useState hook and to change the state just use the setState example:

const [inputValue, setInputValue] = useState ("")
<input value = {inputValue} onChange = {(e) => setInputValue (e.target.value)} />