3

I was trying to run something in useEffect, but did not wanted it to run on initial render so I created a hook useIsMounted.

  import { useRef, useEffect } from 'react';

export const useIsMounted = () => {
    const isMountedRef = useRef(false);
    useEffect(() => {
        console.log(isMountedRef.current);//prints false on first render and true on second render.
        isMountedRef.current = true;
    }, []);
console.log(isMountedRef.current);//prints false on both renders
    return isMountedRef.current;
};

Here I have put two console logs and I am getting different values on two renders(one caused by strict mode) while the one outside useEffect returns same value on both renders.

Also whenever I use useState instead of useRef it console log's same value (false) on both render outside and inside of the useEffect.

here is the sample

import { useEffect, useState } from 'react';

export const useIsMounted = () => {
    const [isMounted, setIsMounted] = useState(false);
    useEffect(() => {
        console.log(isMounted); //prints false on both renders
        setIsMounted(true);
    }, []);
    console.log(isMounted);//prints false on both renders
    return isMounted;
};
rahul
  • 31
  • 2
  • With Strict Mode starting in React 18, whenever a component mounts in development, React will simulate immediately unmounting and remounting the component: * React mounts the component. * Layout effects are created. * Effect effects are created. * React simulates effects being destroyed on a mounted component. * Layout effects are destroyed. * Effects are destroyed. * React simulates effects being re-created on a mounted component. * Layout effects are created * Effect setup code runs On the second mount, React will restore the state from the first mount. – rahul May 20 '22 at 15:27
  • With these reasons it is clear that while re-mounting , the state is restored from the first mount. [strict-mode](https://reactjs.org/docs/strict-mode.html) _italic_ and since I wasn't using the function version for setState I was accessing the stale value of isMounted. So I was getting false on both renders – rahul May 20 '22 at 15:31

0 Answers0