File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments