I want to start a timer interval in react native without using useEffect hook, in y case I want to start a timer when a promise resolves and change a state variable each second, how can I do this without using useEffect hook?
i tried this:
useEffect(
() => {
const id = setInterval(() => {
setCounter(counter+1)
}, 1000);
return () => {
clearInterval(id);
};
},
[] // empty dependency array
);
And while it works I need to start the timer calling it from a normal function and not a hook.
Any side effects (including starting a timer) should not belong to the main body of the component function. Instead, it is best to delegate these things to a useEffect()
hook.
If I understood your question correctly, you can still start that timer inside a hook, simply call the normal function inside.
Eg it can be this simple if your normal function already returns a function to clean itself:
useEffect(() => startTimer(setCounterCallback), [])
Oh, and if the plan is to start it after a promise resolves, also wrap that async function inside the same useEffect()
:
useEffect(() => {
const promise = Promise.resolve();
promise.then(() => startTimer(setCounterCallback));
}, []);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.