useEffectEvent
Extract the non-reactive parts of an Effect into reusable Event functions. Fix stale closure bugs where you need to read the latest prop value inside an effect without making it a reactive dependency.
Stale closures in Effects
When an Effect needs to read a prop but only re-run when something else changes, you're forced into a dilemma: add the prop to deps (unwanted re-runs) or suppress the lint warning (stale bug).
// ❌ PROBLEM: stale closure bug
// 'url' must be in the dependency array → re-runs on every URL change
// But you only want to log when count changes, not when url changes
function useAnalytics(url: string) {
const [count, setCount] = useState(0)
useEffect(() => {
// url is read inside the effect, so it MUST be in deps
fetch('/api/log', { body: JSON.stringify({ url, count }) })
}, [url, count]) // ← url here causes unwanted re-runs!
}useEffectEvent to the rescue
useEffectEvent wraps the non-reactive part. The returned function always reads the latest values at call time, but it's never listed as a dependency — it's intentionally excluded.
// ✅ SOLUTION: useEffectEvent — React 19.2
// Separate the "reactive" part (count) from the "non-reactive" part (url)
import { useEffect, useEffectEvent } from 'react'
function useAnalytics(url: string) {
const [count, setCount] = useState(0)
// onVisit reads the LATEST url at call time, but is NOT reactive
// It will NOT be listed in useEffect's dependency array
const onVisit = useEffectEvent((count: number) => {
fetch('/api/log', { body: JSON.stringify({ url, count }) })
// ↑ always the latest value
})
useEffect(() => {
onVisit(count) // ← onVisit is excluded from deps, count is reactive
}, [count]) // Only re-runs when count changes ✅
}Scroll analytics logger
The scroll handler is set up once (empty deps). Changing the "URL" doesn't restart the effect — but every log entry uses the latest URL value because <code>onScroll</code> is an Effect Event.
✅ Change the URL above — the scroll effect does NOT restart (no url in deps). But every new scroll entry uses the latest URL value, thanks to useEffectEvent.
Three rules to remember
// Rules of useEffectEvent:
//
// 1. Call only inside useEffect (not in event handlers or JSX)
// 2. Never pass to other components or hooks
// 3. The returned function reads latest prop/state at CALL TIME, not at hook time
//
// Think of it as: "freeze the logic, not the values"
const onTick = useEffectEvent(() => {
// Reads current count even though count is not in useEffect deps
console.log('Tick', count)
})
useEffect(() => {
const id = setInterval(onTick, 1000)
return () => clearInterval(id)
}, []) // ← empty deps! onTick always sees latest count