React question detail
What are the differences between useEffect and useEvent (experimental)?
useEvent is an experimental hook (not yet stable in React) designed to solve the problem of creating stable event handlers that always access the latest props and state without causing re-renders or needing to be in dependency arrays.
The Problem useEvent Solves
// Problem: onTick changes on every render, causing interval to reset
function Timer({ onTick }) {
useEffect(() => {
const id = setInterval(() => {
onTick(); // Uses stale closure if onTick is not in deps
}, 1000);
return () => clearInterval(id);
}, [onTick]); // Adding onTick causes interval to reset frequently
}
Solution with useEvent (Experimental)
import { useEvent } from 'react'; // Experimental
function Timer({ onTick }) {
const stableOnTick = useEvent(onTick);
useEffect(() => {
const id = setInterval(() => {
stableOnTick(); // Always calls latest onTick
}, 1000);
return () => clearInterval(id);
}, []); // No dependency needed!
}
Key Differences
| Feature | useEffect | useEvent (experimental) |
|---|---|---|
| Purpose | Run side effects | Create stable callbacks |
| Runs | After render | During render (creates function) |
| Returns | Cleanup function | Stable event handler |
| Closure | Captures values at render time | Always accesses latest values |
| Dependencies | Must list all used values | Not needed in other hooks' deps |
Note: Until useEvent is stable, you can use useCallback with useRef as a workaround for stable callbacks.