Reputation: 520
I have this code, i'd like to clearInterval from outside this component (let's assume that I render a button with onClick method that calls clearInterval function). I tried to pass interval value as a ref, but as soon as state updates this value changes.
useEffect(() => {
(intervalRef.current as ReturnType<typeof setInterval> | undefined) = setInterval(() => {
fetch().then((items) => {
items.forEach((item, id) => {
// set state based on the values
});
});
}, 5000);
return () => clearInterval(intervalRef.current);
}, [state]);
I'm also getting eslint warning for return () => clearInterval(intervalRef.current)
, so I assume that it won't clear properly inside this method as well.
"The ref value 'intervalRef.current' will likely have changed by the time this effect cleanup function runs. If this ref points to a node rendered by React, copy 'intervalRef.current' to a variable inside the effect, and use that variable in the cleanup function."
What is the correct approach of such issues in React?
Upvotes: 1
Views: 1215
Reputation: 202638
"The ref value 'intervalRef.current' will likely have changed by the time this effect cleanup function runs. If this ref points to a node rendered by React, copy 'intervalRef.current' to a variable inside the effect, and use that variable in the cleanup function."
This is saying to save a reference to the ref value in the useEffect
hook's callback closure, to be used in the cleanup function.
useEffect(() => {
(intervalRef.current as ReturnType<typeof setInterval> | undefined) = setInterval(() => {
fetch().then((items) => {
items.forEach((item, id) => {
// set state based on the values
});
});
}, 5000);
const timerId = intervalRef.current;
return () => clearInterval(timerId);
}, [state]);
If you need to, or want to, clear the interval from anywhere else in the component scope, just clear the interval as you would normally with the current ref value:
clearInterval(intervalRef.current);
Upvotes: 1
Reputation: 464
useEffect(() => {
const intervalId = setInterval(() => {
fetch().then((items) => {
items.forEach((item, id) => {
// set state based on the values
});
});
}, 5000);
return () => clearInterval(intervalId);
}, [state]);
You dont need to make it a ref, if all you want is to clean the interval on unmount. Just assign it to a variable and pass it to your cleanup function.
Note: i see you are planning on doing a state update in promise. you might run into issue where component is unmounted and then the promise callback is triggered which tries to update state. so maybe put a isMounted check
Upvotes: 2