Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

107
Vistas
Why does running a callback from useEffect print the wrong value

I'm trying to understand this weird behavior:

  const [counter, setCounter] = useState<number>(1);
  useEffect(() => {
    setCounter(2);

    setTimeout(function () {
      console.log('counter = ', counter); // => counter = 1
    }, 1000);
  }, []);
about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Your effect will be called when your component is first mounted, cause you're passing empty array of deps ... where your counter variable is 1

setCounter function is an async function, react-native ui will push that call into the stack of function-calls that's supposed to be called in order, but the the first function call pushed into that stack of calls is your console.log, with a copy of the value of counter variable which is 1

If you want to print the updated value of counter, put counter to the list of deps like:

const [counter, setCounter] = useState<number>(1);
useEffect(() => {
  setCounter(2);
}, []);
useEffect(() => {
  setTimeout(function () {
    console.log('counter = ', counter); // => counter = 1
  }, 1000);
}, [counter]);
about 4 years ago · Santiago Trujillo Denunciar

0

What is worth mentioning, you are using counter state value inside useEffect. This is targeted by ESLint with default settings. Your useEffect depends on that state and it should be added to dependency array.[ESLint error][1]

This correct usage of useEffect would cause useTimeout to run 2 times. On initial render and after rerender. [1]: https://i.stack.imgur.com/yiLJi.png

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda