V
V
vadimparinov2021-09-13 20:40:38
React
vadimparinov, 2021-09-13 20:40:38

Is it possible to use slice in React?

Please answer the question)
Is it correct to use slice to change the state in react? I read on some resources that this mutates the state, but in theory it returns a new array without changing the original
one. Please tell me the correct answer)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Yarkov, 2021-09-13
@yarkov

The dock is written in Russian . Nothing is mutated.

S
Sergey Suntsev, 2021-09-14
@GreyCrew

You can use it, but do not forget that slice, that spread operator they make a copy of only a flat object (array).

const arr = [0, 1, [2,3]]
const newArr = arr. slice(0)
newArr[2][0] = 'new data'
console.log(arr[2][0]) // new data

If you need to avoid mutation for a deep object, then either JSON.stringify, JSON.parse, or cloneDeep from lodash is used. Or you can write an object traversal function yourself.
There are also specialized immutable(deprecated) or immerjs libraries.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question