ReactJS Hook Pattern ~useEffectEvent Pattern~
Source: Dev.to
Overview
useEffectEvent is introduced in React 19. This hook allows you to access the latest values of props or state inside an effect without causing the effect to re‑run.
A common issue in React is unnecessary re‑rendering when values are listed in the dependency array. useEffectEvent solves this by extracting those values from the dependencies and providing them as arguments to the callback.
Example
import { useState, useEffect, useEffectEvent } from "react";
function trackPage(url, itemCount) {
console.log(`Url: ${url} | Items in cart: ${itemCount}`);
}
function Page({ url }) {
const [itemCount, setItemCount] = useState(0);
// useEffectEvent gives access to the latest `itemCount` without
// needing to list it in the effect dependencies.
const onVisit = useEffectEvent(() => trackPage(url, itemCount));
useEffect(() => {
onVisit();
}, [url]); // `itemCount` is omitted from the dependency array
return (
<div>
<h2>Current Page: {url}</h2>
<p>Items in cart: {itemCount}</p>
<button onClick={() => setItemCount(itemCount + 1)}>
Add Item to Cart
</button>
<button
onClick={() => setItemCount(0)}
disabled={itemCount === 0}
>
Clear Cart
</button>
</div>
);
}
function App() {
const [url, setUrl] = useState("/home");
return (
<div>
<button onClick={() => setUrl("/home")}>Home</button>
<button onClick={() => setUrl("/cart")}>Cart</button>
<button onClick={() => setUrl("/about")}>About</button>
<Page url={url} />
</div>
);
}
export default App;