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

317
Vistas
React : How to call setState twice if the second relies on the first?

How do I achieve this simple logic in react if the second setState hook depends on thee first one to change first? In this example, the first setState value doesn't update fast enough before running the second setState. I have tried putting the second one in a timeout, as well as putting it inside a callback function of the first. Didn't work out. The useEffect might solve this issue but in this particular instance I would need to call useEffect only in the first one and not every time there is a state change. Let me know your thoughts.

function blah(arg) {
    if (condition) {
        setState(arg)
    }
    setState(state + 1)
}
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

React's State isn't meant to work as a variable. When you call setState, you are simply telling the code what value it is supposed to use in the next rendering of the component. It will never set the value immediatly.

If you need it to behave as a variable, just use variables and call setState a single time at the end.

function blah(arg) {
    let aux = state;
    if (condition) {
        aux = arg;
    }
    setState(aux + 1);
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

you need to use the useEffect hook :

const [state, setState] = useState();

useEffect(() => {
    // get executed  whenever state is changed
}, [state])


function blah(arg) {
    if (condition) {
        setState(arg)
    }
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

First Load up on the function

import React, { useState, useEffect } from 'react';

Then

const [ListValue, setListValue] = useState([]);
  
useEffect(() => {
    console.log(ListValue)
}, [])


function blah(arg) {
    if (condition) {
        setListValue(arg)
    }
}
about 4 years ago · Juan Pablo Isaza 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