Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I copy the state in react without reference? [duplicate]

When I want to copy the state like this:

let copy = this.state.foo
copy.push('bar')

the state copied correctly, but with its reference, and when I change 'copy' the main state changes.

What should I do to avoid this change?

like image 704
Mahdi Avatar asked Jul 20 '18 14:07

Mahdi


People also ask

How do you clone a state in React?

To create a deep copy of an object in React, install and use the lodash. clonedeep package. The cloneDeep method recursively clones a value and returns the result. Copied!

How do I not include duplicate values in a React state array?

To remove the duplicates from an array in React, pass the array to the Set constructor, e.g. [... new Set(arr)] . Each value in a Set has to be unique, so any duplicates get automatically removed.

How do you avoid mutating state in React?

In React, the state is immutable. In simple terms it means that you should not modify it directly. Instead a new object should be created to set the state using setState .


1 Answers

You can use array spread or Array.concat() to make a shallow clone, and add new items as well):

const state = {
  foo: ['bar']
};

const copy = [...state.foo, 'bar'];

console.log(copy === state.foo); // false
like image 155
Ori Drori Avatar answered Nov 03 '22 01:11

Ori Drori