UNPKG

783 BJavaScriptView Raw
1import { useEffect, useLayoutEffect, useRef } from 'react';
2
3/**
4 * Returns ref that is `true` on the initial render and `false` on subsequent renders. It
5 * is StrictMode safe, so will reset correctly if the component is unmounted and remounted.
6 *
7 * This hook *must* be used before any effects that read it's value to be accurate.
8 */
9export default function useIsInitialRenderRef() {
10 const effectCount = useRef(0);
11 const isInitialRenderRef = useRef(true);
12 useLayoutEffect(() => {
13 effectCount.current += 1;
14 if (effectCount.current >= 2) {
15 isInitialRenderRef.current = false;
16 }
17 });
18
19 // Strict mode handling in React 18
20 useEffect(() => () => {
21 effectCount.current = 0;
22 isInitialRenderRef.current = true;
23 }, []);
24 return isInitialRenderRef;
25}
\No newline at end of file