Sub topic 1
Event Handlers Respond to Interactions, Effects Synchronize
Prerequisites
Assume you know JavaScript functions and closures, React function components, props, state, useState, and basic useEffect cleanup. You should also know that a dependency array controls when an Effect runs again.
Event Handlers Respond to Interactions, Effects Synchronize
An event handler runs because the user does something, such as clicking a button or typing. It describes one interaction.
An Effect synchronizes a component with something outside React. Examples include a chat connection, browser subscription, timer, or network request. React runs the Effect after rendering and runs its cleanup before synchronization changes or the component unmounts.
function ChatRoom({ roomId }) {
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]);
}This Effect keeps the chat connection synchronized with roomId. It is not responding to a particular click.
What Makes a Value Reactive
A reactive value is a prop, state value, or value declared inside a component that can change between renders. For example, roomId is reactive because a parent can pass a new value. State such as isMuted is reactive because a setter can change it.
Logic that reads a reactive value usually becomes reactive too. If an Effect reads roomId, it needs to synchronize again when roomId changes. React uses the dependency array to express that relationship.
How Dependencies Make Effects Re-synchronize
Each dependency tells React which changes matter to the Effect.
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]);When roomId changes, React cleans up the old connection and creates a new one. When unrelated state changes, React leaves the connection alone.
When an Effect Reconnects for the Wrong Reason
Suppose the connection displays a notification using theme:
useEffect(() => {
const connection = createConnection(roomId);
connection.on('connected', () => {
showNotification('Connected!', theme);
});
connection.connect();
return () => connection.disconnect();
}, [roomId, theme]);Changing the theme now disconnects and reconnects the chat, even though the chat room did not change. The notification needs the latest theme, but the connection does not need to be recreated. The next chapter shows how useEffectEvent separates these two kinds of logic.
Exercise
Which change should re-synchronize the chat connection: a new roomId or a new theme used only to style a notification?
Show answer
A new roomId should re-synchronize the connection. The notification can read the latest theme without recreating that connection.