Next.js Discord

Discord Forum

useEffect, Strict Mode, stop from running twice

Unanswered
Virginia's Warbler posted this in #help-forum
Open in Discord
Avatar
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.

  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

Avatar
This only happens in dev
Avatar
Virginia's WarblerOP
So there aint a code-based solution?
Avatar
there is
Avatar
Virginia's WarblerOP
PS, im using "react": "18.2.0"
How?
Avatar
using use ref
Avatar
Virginia's WarblerOP
I tried debounce & callback.
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?
Avatar
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;
Avatar
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
Avatar
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
Avatar