useStaticEffectEvent.ts18 lines · main
1// @ts-nocheck
2import { useEffect, useRef } from 'react'
3
4/**
5 * Like useEffect but the callback is NOT invalidated when deps change.
6 * The callback captured at first render is called on every dep change.
7 * Useful for event handlers that should always see the latest deps
8 * without being re-registered.
9 */
10export function useStaticEffectEvent<T extends (...args: any[]) => any>(fn: T): T {
11 const ref = useRef<T>(fn)
12 ref.current = fn
13 const stableRef = useRef<T>()
14 if (!stableRef.current) {
15 stableRef.current = ((...args: any[]) => ref.current(...args)) as T
16 }
17 return stableRef.current
18}