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

325
Visualizações
React - State variable inside cleanup function

Please look at App.js file for a react app created through create-react-app

import { useState, useEffect } from "react";
 
function App() {
  const [pState, setPState] = useState(false);
 
  useEffect(() => {
    console.log('Use effect parent. ' + pState);
 
    return () => {
      console.log('Parent cleanup function called. Current State: ' + pState);
    }
  }, [pState]);
 
  const pChangeHandler = () => {
    setPState(prevP => {
      return !prevP;
    })
  }
 
  console.log('Parent component rendered. ' + pState);
  return (
    <div className="App">
      <button onClick={pChangeHandler}>Change P State</button>
    </div>
  );
}
 
 
export default App;

After clicking the button 1 time, following is my console output (first 2 consoles are before clicking the button) enter image description here

When the button is clicked, I get 'parent component rendered' with pState as true. So I expected it to be true(as it is called after the rendering happens and pState while rendering is true) in the 'Parent cleanup function...' called log as well. 'Use effect parent' log has pState true as well.

Could someone please explain this behavior?

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

0

From the docs:

React cleans up the effect from previous render before running the next render.

The false value that is logged is from the useEffect cleanup from the previous render (when pState was false).

Docs

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