Today I Learned

hashrocket A Hashrocket project

React 19.2 new useEffectEvent hook

React 19.2 added a new hook useEffectEvent that lets us to extract event handlers from effects, so they use the latest props/state without triggering effect re-runs.

Problem: You want an effect to depend on roomId but not theme:

function ChatRoom({ roomId, theme }) {
  useEffect(() => {
    const connection = createConnection(roomId).then(() => {
      showNotification('Connected!', theme);
    });

    return connection.disconnect;
  }, [roomId, theme]);
}

Solution with useEffectEvent:

function ChatRoom({ roomId, theme }) {
  const onConnected = useEffectEvent(() => {
    showNotification('Connected!', theme);
  });

  useEffect(() => {
    const connection = createConnection(roomId).then(() => {
      onConnected();
    });

    return connection.disconnect;
  }, [roomId]);
}

This way if the theme changes nothing happens, but if the roomId changed then a notification is fired with the latest theme value.

See More #react TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.