Open History to see the last commit
1import { useRef, useState, type EffectCallback } from 'rehackt'
2import { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect'
3β
4/**
5 * This hook handles StrictMode and prod mode
6 */
7export const useIsomorphicEffectOnce = (effect: EffectCallback) => {
8 const destroyFunc = useRef<void | (() => void)>()
9 const effectCalled = useRef(false)
10 const renderAfterCalled = useRef(false)
11 const [val, setVal] = useState(0)
12β
13 if (effectCalled.current) {
14 renderAfterCalled.current = true
15 }
16β
17 useIsomorphicLayoutEffect(() => {
18 // only execute the effect first time around
19 if (!effectCalled.current) {
20 destroyFunc.current = effect()
21 effectCalled.current = true
22 }
23β
24 // this forces one render after the effect is run
25 setVal((v) => v + 1)
26β
27 return () => {
28 // if the comp didn't render since the useEffect was called,
29 // we know it's the dummy React cycle
30 if (!renderAfterCalled.current) {
31 return
32 }
33 if (destroyFunc.current) {
34 destroyFunc.current()
35 }
36 }
37 }, [])
38}