Answer the question
In order to leave comments, you need to log in
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
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]
Answer the question
In order to leave comments, you need to log in
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question