Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why setInterval logs exponentially for every re-render ? Please help me, i need to understand this code

function ParentComp(props){
  console.log("rendering parent");
  const [person, setPerson] = useState({ firstName: "First" });  
  setInterval(() => {
    setPerson({ firstName: "Second" });
  }, 6000);
  return (
    <>     
      <ChildComp name={person.firstName} />
    </>
  );
}
function ChildComp({ name }){
  console.log("Rendering child");
  return <div>{name}</div>;
}
export default ParentComp;

console log , logs exponentionally

I expect the console log to log consecutively, but i found that it is rerendering the parent and child components exponentially like 2times, 4times, 8 times ..so on. I need to understand why it is so. I am new to react. please help me to understand. Thanks in Advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Becase you are calling setInterval in your component and not in useEffect there is new interval every rerender, because all that code is called every render.

If you want to have setInterval in react, you need to use it in useEffect and in cleanup function of useEffect, you need to remove this interval:

function ParentComp(props){
  console.log("rendering parent");
  const [person, setPerson] = useState({ firstName: "First" });
  var i = 0;
  React.useEffect(()=>{
 const interval =   setInterval(() => {
    setPerson({ firstName: "Second" });
  }, 6000);
    return ()=>clearInterval(interval);
  },[])

  return (
    <>
      {person.firstName}
      <ChildComp name={person.firstName} />
    </>
  );
}
function ChildComp({ name }){
  console.log("Rendering child");
  return <div>{name}</div>;
}
export default ParentComp;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading