Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

224
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!