Answer the question
In order to leave comments, you need to log in
Why in React, to change useState, many people write like this setState(pre => pre = data), and not just like this setState(data)?
Good day dear developers. I am a junior developer writing React js, I wrote a couple of projects. Every React developer will work with the useState hook. To change the state of the hook, I write setState(data), somewhere I saw that some people write setState(pre => pre = data) like this. And of course I want to know why it is written that way. Maybe it optimizes the application?
Answer the question
In order to leave comments, you need to log in
Sometimes it can optimize. for example
const [x, setX] = useState(0);
const f = useCallback(() => setX(x => x + 1), []);
setState(pre => pre = data)
- this is nonsense nonsense.
setState(pre => {
const data = <что-делаем с pre>;
return data;
})
- another thing. Such a function does not depend on external data, only on the previous state.
The way you present it doesn't make sense. Why the function is used is described in the documentation.
https://reactjs.org/docs/hooks-reference.html#func...
Functional updates
If the new state is computed using the previous state, you can pass a function to setState. The function will receive the previous value, and return an updated value. Here's an example of a counter component that uses both forms of setState:
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question