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

229
Visualizações
Component State is not changing inside setInterval

I am running a function that downloads the data from the server and runs it after an interval with the help of setInterval. The issue is that I am unable to change the state of the component inside the setInterval(inside the function I have defined). I need this state to be changed because Child component needs to re-render a few things whenever downloads happen.

Here is the similar code (just for demo purpose) which demonstrate the problem I am facing.

import React, { useState, useEffect, useRef, useReducer } from 'react';
import './App.css';
import Child from './Child';

const App = () => {
  const [reset, setReset] = useState(false);

  const changeState = () => {
    console.log('changing state from', reset);
    setReset(!reset);
    console.log('changing state to', reset);
  };

  const init = () => {
    setInterval(changeState, 1000);
  };

  return (
    <>
      <button onClick={init}>Start</button>
      <button onClick={changeState}>Change</button>
      <Child reset={reset} />
    </>
  );
};

export default App;

  1. When you click the Change button state of the button changes perfectly.
  2. but if you click start button (click it once), it will start calling the setReset to change the state but it has no impact. This is how the output looks like in this case.

enter image description here

Child component

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


const Child = (props) => {
    
    return (
      <>
       {props.reset ? "hello" : "tello"}
      </>
    );
};


export default Child;

You can edit the code here https://stackblitz.com/edit/react-aj5wdf?devtoolsheight=33&file=src/App.js

Note: I have beginner-level experience with React.

Thanks.

about 4 years ago · Juan Pablo Isaza
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