useEffect, Strict Mode, stop from running twice
Unanswered
Virginia's Warbler posted this in #help-forum
Virginia's WarblerOP
This issue is driving me crazy. If anyone can give me a code solution (ie: other than turn off Strict or run in Prod), it'd be so appreciated.
Even after imitating this guy's helpful tutorial https://youtu.be/81faZzp18NM?si=anRDjGT_TxQF5R55 , it still didnt work. Stuff in useEffect ran 2x anyways. Both his solutions 1 & 2 didnt work for me.
Even after imitating this guy's helpful tutorial https://youtu.be/81faZzp18NM?si=anRDjGT_TxQF5R55 , it still didnt work. Stuff in useEffect ran 2x anyways. Both his solutions 1 & 2 didnt work for me.
const toastOnce = useRef(false);
useEffect(() => {
if (useToast.current === true) {
// THE THING THAT SHOULD RUN ONCE
}
return () => {
useToast.current = true
}
}, []);
const toastOnce = useRef(false);
useEffect(() => {
if (useToast.current === false) {
// THE THING THAT SHOULD RUN ONCE
return () => {
useToast.current = true
}
}
}, []);
16 Replies
This only happens in dev
Virginia's WarblerOP
So there aint a code-based solution?
there is
Virginia's WarblerOP
PS, im using
"react": "18.2.0"
How?
using use ref
Virginia's WarblerOP
I tried debounce & callback.
I tried the one I wrote above.
Nothing worked
I tried the one I wrote above.
Nothing worked
I tried the one I wrote above.Thats what I tried
Either it didnt work. Or I did something wrong (which I dont see)
Do you see if I did something wrong?
import { useEffect, useRef } from 'react';
const useEffectOnce = (callback,deps) => {
const hasRun = useRef(false);
useEffect(() => {
if (!hasRun.current) {
callback();
hasRun.current = true;
}
}, deps);
};
export default useEffectOnce;
Virginia's WarblerOP
Thank you, let me try
So the only diff between your and mine is instead of
if (useToast.current === false)
, you have if (!useToast.current)
I wonder that makes the difference
Virginia's WarblerOP
Actually, no. Sorry but that did not work.
I imitated your code "one to one", but no, the 2x problem still happened
I imitated your code "one to one", but no, the 2x problem still happened
https://codesandbox.io/p/devbox/6xl4z3
it works for me
it works for me