11---
2- title : useLatest for Stable Callback Refs
2+ title : useEffectEvent for Stable Callback Refs
33impact : LOW
44impactDescription : prevents effect re-runs
5- tags : advanced, hooks, useLatest , refs, optimization
5+ tags : advanced, hooks, useEffectEvent , refs, optimization
66---
77
8- ## useLatest for Stable Callback Refs
8+ ## useEffectEvent for Stable Callback Refs
99
1010Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
1111
12- ** Implementation:**
13-
14- ``` typescript
15- function useLatest<T >(value : T ) {
16- const ref = useRef (value )
17- useLayoutEffect (() => {
18- ref .current = value
19- }, [value ])
20- return ref
21- }
22- ```
23-
2412** Incorrect (effect re-runs on every callback change):**
2513
2614``` tsx
@@ -34,15 +22,17 @@ function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
3422}
3523```
3624
37- ** Correct (stable effect, fresh callback ):**
25+ ** Correct (using React's useEffectEvent ):**
3826
3927``` tsx
28+ import { useEffectEvent } from ' react' ;
29+
4030function SearchInput({ onSearch }: { onSearch: (q : string ) => void }) {
4131 const [query, setQuery] = useState (' ' )
42- const onSearchRef = useLatest (onSearch )
32+ const onSearchEvent = useEffectEvent (onSearch )
4333
4434 useEffect (() => {
45- const timeout = setTimeout (() => onSearchRef . current (query ), 300 )
35+ const timeout = setTimeout (() => onSearchEvent (query ), 300 )
4636 return () => clearTimeout (timeout )
4737 }, [query ])
4838}
0 commit comments