Skip to content

Commit 2f92f86

Browse files
committed
minor: Add useEffectEvent polyfill
1 parent 17f9991 commit 2f92f86

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

site/src/hooks/hookPolyfills.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* @file For defining DIY versions of official React hooks that have not been
3+
* released yet.
4+
*
5+
* These hooks should be deleted as soon as the official versions are available.
6+
* They also do have the same ESLinter exceptions baked in that the official
7+
* hooks do.
8+
*/
9+
import { useCallback, useEffect, useRef } from "react";
10+
11+
/**
12+
* A DIY version of useEffectEvent.
13+
*
14+
* Works like useCallback, except that it doesn't take a dependency array, and
15+
* always returns out a stable function on every single render. The returned-out
16+
* function is always able to "see" the most up-to-date version of the callback
17+
* passed in.
18+
*
19+
* Should only be used as a last resort where useCallback does not work, and you
20+
* still need to avoid dependency array violations.
21+
*
22+
* @see {@link https://react.dev/reference/react/experimental_useEffectEvent}
23+
*/
24+
export function useEffectEvent<TArgs extends unknown[], TReturn = unknown>(
25+
callback: (...args: TArgs) => TReturn,
26+
) {
27+
const callbackRef = useRef(callback);
28+
useEffect(() => {
29+
callbackRef.current = callback;
30+
}, [callback]);
31+
32+
return useCallback((...args: TArgs): TReturn => {
33+
return callbackRef.current(...args);
34+
}, []);
35+
}

0 commit comments

Comments
 (0)