D
D
Dosya2022-01-15 08:00:47
React
Dosya, 2022-01-15 08:00:47

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

3 answer(s)
A
Alexandroppolus, 2022-01-15
@Dasihub

Sometimes it can optimize. for example

const [x, setX] = useState(0);
const f = useCallback(() => setX(x => x + 1), []);

Here f is the same, not recreated for each new x. If f is passed to the props of a memo component, it will not be updated unless it depends on x.

A
Aetae, 2022-01-15
@Aetae

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.

V
Vladimir, 2022-01-15
@Casufi

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 question

Ask a Question

731 491 924 answers to any question