R
R
raury2020-12-20 12:16:01
React
raury, 2020-12-20 12:16:01

Why is a callback used when calling the state change function from useState?

const [value, setValue] = useState(null)
//...
function handler(newValue) {
  setValue(() => newValue)
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
Gary_Ihar, 2020-12-20
@raury

Here is the answer

M
Maxim Kirshin, 2020-12-20
@meowto16

In your example, it makes no sense.
And so it is usually used to set the state based on the previous value of the state

function handler(newValue) {
  setValue((prevState) => prevState + 1) // Установит стейт на основании предыдущего значения + 1
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question