0

Is there any way to know whether the strict mode is enabled in React?

useEffect(() => {

  if(strictModeEnabled) {}

})

I didn't find any information in the docs.

6
  • Why do you need this? Commented May 24, 2022 at 6:03
  • I have a cleanup logic that should run only once. It doesn't work now with the change in v18 where effects running twice. Commented May 24, 2022 at 6:06
  • with refs you can understand is your running first or twice @undefined Commented May 24, 2022 at 6:09
  • No, because the clean-up always runs once. @HakobSargsyan Commented May 24, 2022 at 6:10
  • Check my answer @undefined Commented May 24, 2022 at 6:12

1 Answer 1

0

You can use this

export const useEffectOnce = ( effect )=> {

  const destroyFunc = useRef();
  const effectCalled = useRef(false);
  const renderAfterCalled = useRef(false);
  const [val, setVal] = useState(0);

  if (effectCalled.current) {
      renderAfterCalled.current = true;
  }

  useEffect( ()=> {

      // only execute the effect first time around
      if (!effectCalled.current) { 
        destroyFunc.current = effect();
        effectCalled.current = true;
      }

      // this forces one render after the effect is run
      setVal(val => val + 1);

      return ()=> {
        // if the comp didn't render since the useEffect was called,
        // we know it's the dummy React cycle
        if (!renderAfterCalled.current) { return; }
        if (destroyFunc.current) { destroyFunc.current(); }
      };
  }, []);
};

call it by

useEffectOnce( ()=> {
    console.log('my effect is running');
    return () => console.log('my effect is destroying');
});

Read more here

Sign up to request clarification or add additional context in comments.

7 Comments

This isn't the ultimate solution as it causes a redundant render cycle. I prefer to check somehow whether strict mode is enabled
Your cleanup is only for development ? @undefined
No, for both production and dev
StrictMode is a developer tool, it runs only in development mode. It does not affect the production build in any way whatsoever. In order to identify and detect any problems within the application and show warning messages, StrictMode renders every component inside the application twice. @undefined , in the production everything will be good for you
I can't work in dev mode, I need it to run only once
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.