useStaticEffectEvent.ts 606 B

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