I am trying to create a loading component that will add a period to a div periodically, every 1000ms using setInterval in React. I am trying to cleanup setInterval using the met
Dependencies are our hint for React of when the effect should run, even though we set an interval and providing no dependencies []
, React wont know we want to run it more then once because nothing really changes in our empty dependencies []
.
To get the desired result we need to think when we want to run the effect ?
We want to run it when loadingStatus
changes, so we need to add loadingStatus
as our dependency because we want to run the effect every time loadingStatus
changes.
We have 2 options
Add loadingStatus
as our dependency.
const Loading = () => {
const [loadingStatus, setLoadingStatus] = useState(".");
const [loop, setLoop] = useState();
useEffect(
() => {
setLoop(
setInterval(() => {
console.log("loading");
setLoadingStatus(loadingStatus + ".");
}, 1000)
);
return function cleanup() {
console.log("cleaning up");
clearInterval(loop);
};
},
[loadingStatus]
);
return <p>{`Loading ${loadingStatus}`}</p>;
};
Make our effect not aware that we use loadingStatus
const Loading = () => {
const [loadingStatus, setLoadingStatus] = useState(".");
useEffect(() => {
const intervalId = setInterval(() => {
setLoadingStatus(ls => ls + ".");
}, 1000);
return () => clearInterval(intervalId);
}, []);
return <p>{`Loading ${loadingStatus}`}</p>;
};
Read more here => a-complete-guide-to-useeffect