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

324
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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