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;
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.
CodePudding user response:
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;