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

80
Visualizações
React function doesn't updated with state

I'm trying to execute a function that is using react state but when state changes the function doesn't updates with the state value.

    const {useState, useEffect} = React;

function Example() {
  const [count, setCount] = useState(0);
  
  const testFunction = function(){
        setInterval(() => {
        console.log(count)
    }, 3000)
  }
  useEffect(() => {
let fncs = [testFunction];

fncs.forEach(fnc => fnc.apply(this));
  }, [])
  


  // Similar to componentDidMount and componentDidUpdate:  
  useEffect(() => {   
    // Update the document title using the browser API    
    document.getElementById('other-div').innerHTML = `You clicked ${count} times`;  
  });
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

ReactDOM.render( <Example />, document.getElementById('root') );

Exmaple: https://jsfiddle.net/bzyxqkwt/4/

just so you understand, im passing functions to another component and he execute those functions on some event like this

fncs.forEach(fnc => fnc.apply(this, someEventParams));
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I'm just guessing that the setInterval is just for demo purposes and needs to be stopped/removed, but basically useEffect captures the initial state. So if you want to catch inside the inner function updated state, then you should pass all the values that you need (in this case count parameter). Something like:

const testFunction = function(){
    // setInterval(() => {
        console.log(count); // it should log the updated value
    // }, 3000)
  }
  useEffect(() => {
     let fncs = [testFunction];

      fncs.forEach(fnc => fnc.apply(this));
  }, [count]);   // <-- this makes the trick
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