・The useEffectEvent is introduced in ReactJS 19. This hook enables access to the latest values of other props or state without causing the Effect to re-run. There has been a common problem that unnecessary re-rendering occurs due to the dependency array. The useEffectEvent solves the problem by extracting unnecessary values from the dependencies, and using them as an argumensts.
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);
const onVisit = useEffectEvent( (url) => trackPage(url, itemCount))
useEffect(() => {
onVisit(url);
}, [url]); //Remove itemCount 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>
<div>
<button onClick={() => setUrl("/home")}>Home</button>
<button onClick={() => setUrl("/cart")}>Cart</button>
<button onClick={() => setUrl("/about")}>About</button>
</div>
<Page url={url} />
</div>
);
}
export default App;
Top comments (0)