Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
When to use callback useState

It's maybe simple question, but the i'm not fully understand useState

I have confuse with when to use callback with useState, say example, i have an hook

const[count,setCount] = useState(0)

We can easy to update, for example , if i want to update the number, i can do:

setCount(count+1)

But if we have some code like setInterval,we want to increase the count every 1 second, when do the same as above

setTimeout(()=>{
 setCount(count+1)
},1000)
console.log(count)

It will not increase even 1s passed

But we do

 setTimeout(()=>{
     setCount((count)=>{count+1}
    },1000)
    console.log(count)

But why it work???

My question is

When to use callback in useState?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

In React, when you update a state property, with respect to its previous value, you should use,

setState((state,props)=>{ return doSomethingWith(state.property)})

In your code (using hooks): setCount((count)=>(count+1))

This is due to the fact that, state updates may be asynchronous in React.

By the way setCount((count)=>(count+1)) is not the same as setCount((count)=>{count+1}). In the 2nd case, the curly braces form an empty statement, & hence count+1 is not returned. In lambda functions the auto-return happens only in the case of a single expression.

about 4 years ago · Juan Pablo Isaza Relatório

0

Whenever a current state value update depends on the previous state , we can use a callback function.

if we have some code like setInterval,we want to increase the count every 1 second

For setInterval, Each second we need to update the count based on the previous state.This will update the count every 1 second interval.

setInterval(() => { setCount((count) => count + 1); }, 1000);

about 4 years ago · Juan Pablo Isaza Relatório

0

You use the callback when you want to keep the previous state and add something to it.

For example, let's say we have a counter in your case

const [counter, setCounter] = useState(0);

If I want this value to increase every second or when I press a button, I would use the following:

setCounter(prev => (prev + 1);
// Or
setCounter(counter => (counter + 1);

prev will be the same value as counter doesn't matter what you call it.

And since you will be using setInterval you will have to do this operation in a useEffect hook is the reason you will need the callback otherwise if you keep setting the value to counter + 1 without using the callback you will just be 0 + 1 all the time.

Unless you wanna use it for something like increasing a like button counts. In that case you don't need callbacks.

Try reading and understanding those articles and docs:

  • setInterval in react hooks
  • useEffect Hook
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda