Read current props with useEffectEvent
Read the latest props in an Effect Event while keeping a React subscription tied to its real dependencies.
Your chat view subscribes to one room at a time. A message notification uses the current theme, so you put theme in the subscription Effect's dependency array. Now the subscription closes and opens when you switch to dark mode.
Keep the listener tied to the room
The room selects the message source. The theme changes what you do with a message once it arrives. Put that response in an Effect Event and keep the room in the Effect dependencies.
Render this App in a client app using React 19.2 or later. The browser's custom events stand in for a room feed.
import { useEffect, useEffectEvent, useState } from 'react'
function Room({ room, theme }) {
const onMessage = useEffectEvent((message) => {
console.info(theme, message)
})
useEffect(() => {
const event = 'message:' + room
const handleMessage = (e) => onMessage(e.detail)
window.addEventListener(event, handleMessage)
console.info('subscribe', room)
return () => {
window.removeEventListener(event, handleMessage)
console.info('unsubscribe', room)
}
}, [room])
return null
}
export function App() {
const [room, setRoom] = useState('lobby')
const [theme, setTheme] = useState('light')
return (
<>
<button onClick={() => setTheme('dark')}>Dark theme</button>
<button onClick={() => setRoom('support')}>Switch room</button>
<button onClick={() => {
window.dispatchEvent(new CustomEvent('message:' + room, {
detail: 'New reply',
}))
}}>Send message</button>
<Room room={room} theme={theme} />
</>
)
}After the initial subscribe lobby, click Dark theme and then Send message. You get dark New reply without a second subscription. Click Switch room and you see unsubscribe lobby followed by subscribe support. In development Strict Mode, React can run an extra setup and cleanup at mount.
Keep the dependency that selects the source
onMessage reads the latest committed theme, even though the listener was installed with the light theme. Keep the Effect Event out of the dependency array. React can return a new function identity across renders, and the installed listener can still call its Effect Event and read the current theme.
Keep room in the array. Removing it would leave the listener attached to the lobby after the UI switched to support. The same rule applies to a URL or filter that changes which events the subscription receives.
Call the Effect Event from the Effect or a callback the Effect registers. The send button in the example dispatches an event. It has no reason to call the Effect Event itself.
If a theme change also needs to change the actual subscription, let the Effect react to that change. For a display preference used only when a message arrives, put the read in the Effect Event.