forked from
jollywhoppers.com/witchsky.app
Bluesky app fork with some witchin' additions 馃挮
1import {useCallback, useInsertionEffect, useRef} from 'react'
2
3const noop = () => {}
4
5/**
6 * This should be used sparingly. It erases reactivity, i.e. when the inputs
7 * change, the function itself will remain the same. This means that if you use
8 * this at a higher level of your tree, and then some state you read in it
9 * changes, there is no mechanism for anything below in the tree to "react" to
10 * this change (e.g. by knowing to call your function again).
11 *
12 * Also, you should avoid calling the returned function during rendering since
13 * the values captured by it are going to lag behind.
14 *
15 * For objects, see `useNonReactiveObject` instead.
16 */
17export function useNonReactiveCallback<T extends Function = () => void>(
18 fn?: T,
19): T {
20 const ref = useRef<T>((fn ?? noop) as T)
21 useInsertionEffect(() => {
22 ref.current = (fn ?? noop) as T
23 }, [fn])
24 return useCallback(
25 (...args: any) => {
26 const latestFn = ref.current
27 return latestFn(...args)
28 },
29 [ref],
30 ) as unknown as T
31}