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;
};