FrontendDeveloper.in

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

FeatureuseEffectuseEvent (experimental)
PurposeRun side effectsCreate stable callbacks
RunsAfter renderDuring render (creates function)
ReturnsCleanup functionStable event handler
ClosureCaptures values at render timeAlways accesses latest values
DependenciesMust list all used valuesNot needed in other hooks' deps

Note: Until useEvent is stable, you can use useCallback with useRef as a workaround for stable callbacks.

Back to all React questions
Get LinkedIn Premium at Rs 399