[BUG] useUnmount() writes to a ref unsafely during render

Author: VanTanevCreated Apr 8, 2025Updated Jul 12, 2025
Labelsbug

Describe the bug

A ref should never be updated in render.

The corrected hook is:

typescript
export function useUnmount(func: () => void) {
  const funcRef = useRef(func)

  // must be a separate use effect
  useEffect(() => {
    funcRef.current = func
  }, [func])

  useEffect(
    () => () => {
      funcRef.current()
    },
    [],
  )
}

To Reproduce

From the official React docs

Expected behavior

Do not mutate refs in render, because a render can be backed out before it's committed, and the mutated ref with possible incorrect behavior will stick around for the real cleanup

Additional context

No response