D
D
Dmitry Markov2021-04-26 17:30:00
React
Dmitry Markov, 2021-04-26 17:30:00

What is the difference between these ways of changing the state to the opposite?

Why do all the articles (which I have seen) use the first method?

const [data, setData] = useState(false);
Способ 1
setData(prev => !prev); // true
setData(prev => !prev); // false
setData(prev => !prev); // true
Способ 2
setData(!data) // true
setData(!data) // false
setData(!data) // true

or, for example, if you need to add to the array to existing entries
const [data, setData] = useState([1, 2, 3]);
const newData = [4, 5, 6];
setData(prev => [...prev, ...newData]);
// data = [1, 2, 3, 4, 5, 6]
и
setData([...data, ...newData]);
// data = [1, 2, 3, 4, 5, 6]


After all, 'method 2' is shorter. Maybe there is another meaning to this?

Postscript, no offense please)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
n1ksON, 2021-04-26
@n1ksON

It would be better to use the first method.
Using prev (previous state) ensures that the hook works correctly and does not mutate.
To get started, you can see an example here
Read more documentation

N
Nikolay Matyushkin, 2021-04-26
@Devilz_1

Sorry for my laziness))
Read here

A
Anton, 2021-04-26
@karminski

I use only the second method. No problem. This is just a short note.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question