Using useEffectEvent() in React
Introduction
useEffectEvent() is a React hook that allows you to create event handlers that can safely access the latest state and props without needing to include them in the dependency array of useEffect(). This can help prevent issues with stale closures and unnecessary re-renders.
Before React 19.2
useEffectEvent() was introduced in React 19.2. Before this version, developers often faced challenges when trying to access the latest state or props within event handlers defined inside useEffect().
One way to work around this was to use refs to store the latest state or props, but this approach could be cumbersome and error-prone. Learn more about this in this article.
Example
Let’s create a component called Chat.
Note: We will use same example from the article mentioned above to demonstrate how
useEffectEvent()can simplify event handling in React.
import { useState } from "react";
import Chatroom from "./Chatroom";
export default function Chat() {
const [roomId, setRoomId] = useState("1");
const [nightTheme, setNightTheme] = useState(false);
return (
<>
<select value={roomId} onChange={(e) => setRoomId(e.target.value)}>
<option value="1">Room 1</option>
<option value="2">Room 2</option>
<option value="3">Room 3</option>
</select>
<br />
<label>Dark Theme: </label>
<input
type="checkbox"
checked={nightTheme}
onChange={(e) => setNightTheme(e.target.checked)}
/>
<Chatroom roomId={roomId} nightTheme={nightTheme} />
</>
);
}The component above allows the user to select a chat room and toggle a dark theme. The Chatroom component receives roomId and nightTheme as props.
Chatroom Component
Now let’s implement the Chatroom component, which logs a greeting message when the user changes chatrooms.
import { useEffect } from "react";
interface Props {
roomId: string;
nightTheme: boolean;
}
export default function Chatroom({ roomId, nightTheme }: Props) {
useEffect(() => {
if (nightTheme) {
console.log(`Good night from room ${roomId}`);
} else {
console.log(`Good day from room ${roomId}.`);
}
}, [roomId, nightTheme]);
return <div>You are in room {roomId}</div>;
}Get Ye Min Ko’s stories in your inbox
Join Medium for free to get updates from this writer.
In this implementation, the useEffect() hook logs a greeting message whenever roomId changes. The greeting message also depends on the user's selected theme, which is determined by the nightTheme prop. Therefore, both roomId and nightTheme must be included in the useEffect() dependency array.
The problem
We only want to log a greeting message when the user switches chatrooms. However, the greeting message is also logged whenever the user toggles the dark theme.
Solution
To solve this problem, we can use the useEffectEvent() hook to create an event handler that can safely access the latest state and props without needing to include them in the dependency array of useEffect(). Let's update the Chatroom component to use useEffectEvent():
import { useEffect, useEffectEvent } from "react";
interface Props {
roomId: string;
nightTheme: boolean;
}
export default function Chatroom({ roomId, nightTheme }: Props) {
const isNightTheme = useEffectEvent(() => nightTheme);
useEffect(() => {
if (isNightTheme()) {
console.log(`Good night from room ${roomId}`);
} else {
console.log(`Good day from room ${roomId}.`);
}
}, [roomId]);
return <div>You are in room {roomId}</div>;
}As you can see, we have replaced the nightTheme prop with the isNightTheme() function returned by useEffectEvent(). This allows us to access the latest value of nightTheme without including it in the dependency array of useEffect(). Now, the greeting message will only be logged when the user switches chatrooms, and not when they toggle the dark theme.
Conclusion
By using useEffectEvent(), we can create event handlers that safely access the latest state and props without needing to include them in the dependency array of useEffect(). This can help prevent issues with stale closures and unnecessary re-renders, making our React components more efficient and easier to maintain.






