Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

230
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda