why should you clone react state before changing it or when working on it?

Viewed 329

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'})
2 Answers

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.

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)} />
Related