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

136
Visualizações
Update variable and use it immediately React

I am trying to update a variable after an api call but I will use a click event for this question.

As you can see, the variable that i print uses the old state on the first click as it doesn't register the change yet. On the following calls the variable gets printed with the new text.

Is there a way to use the updated variable immediately within the changeText function?

https://stackblitz.com/edit/react-36jqi3

export default function App() {
  const [text, setText] = useState('inital text');

  const changeText = () => {
    setText('new text');
    console.log(text);
  };

  return (
    <div>
      <button onClick={changeText}>Update variable</button>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

No.

The changeText function that is currently running will have closed over the value of text from the value assigned during the render that created the changeText function.

The next render of the component will generate a new changeText function and assign it to onClick.

If you want to use the value you've just passed to setState then keep a copy of that value somewhere else.

const changeText = () => {
  const newValue = 'new text';
  setText(newValue);
  console.log(newValue);
};

Alternatively, do the work that needs the new value in an effect hook that triggers when that value changes.

useEffect(() => {
    console.log(text);
}, [text]);

const changeText = () => {
  setText('new text');
};

That will trigger the hook on the initial render too though so you might want to add an extra test to make sure it isn't the initial value before logging it.

about 4 years ago · Juan Pablo Isaza Relatório

0

Can get by way.

export default function App() {
  

  const [text, setText] = useState('inital text');


  const changeText = () => {
    /* Calling updater to get the latest value. */
    setText('new text');
    setText((state) => {
       console.log("immediately updated text -->", state); 
       return state;
    });
  };



  return (
    <div>
      <button onClick={changeText}>Update variable</button>
    </div>
  );
}
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