how to stop the loadFriendList when setWorker Value is"0"?
const [worker, setWorker] = useState('1');
function start() {
setInterval(loadFriendList,5000);
}
useEffect(start, []);
function n() {
setWorker("0");
Alert.alert('check', worker);
}
Don't use strings as number it's an unnecessary hassle .
use
useRef
hook to store intervalID .
This useEffect
hook fires whenever worker is change.
see inside the
[]
we've added worker variable. It's called dependancy array. Basically you're saying to useEffect look on these variables and fire if anything changes
useEffect(() => {
if(worker == 0) intID.current && clearInterval(intId.current)
},[worker])
The useRef
hook is holding on to the Interval you set up when page loading, to uniquely identify and run methods like clearInterval()
in future
const [worker, setWorker] = useState(1);
const intId = useRef(null)
useEffect(() =>{
intId.current = setInterval(loadFriendList,5000);
return () => clearInterval(intId.current)
}, []);
useEffect(() => {
if(worker == 0) intId.current && clearInterval(intId.current)
},[worker])