When Effects Are Actually Needed After Events
You'll learn: When it's legitimate to combine event handlers with useEffect to synchronize with external systems after user actions.
The Rare Exception to the Rule
We've spent several lessons moving logic out of effects and into event handlers. But there's one legitimate pattern where both work together: when an event handler updates state, and that state change needs to synchronize with an external system.
The key word is external. This means non-React systems like:
- Browser APIs (focus, scroll position, localStorage)
- Third-party libraries (analytics, chat widgets, maps)
- WebSocket connections
- Canvas rendering
The Pattern
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
const [isConnected, setIsConnected] = useState(false);
// Effect: Synchronize with external chat service
useEffect(() => {
const connection = chatService.connect(roomId);
setIsConnected(true);
return () => {
connection.disconnect();
setIsConnected(false);
};
}, [roomId]);
// Event handler: User action updates state
function handleSend() {
chatService.send(message);
setMessage(''); // Clear input
// Effect will see isConnected is true and can react if needed
}
}
Here, the event handler does its job (send message, update state), while the effect maintains the connection. They complement each other.
When NOT to Use This
If you're just updating React state or calculating values, it all belongs in the event handler. Effects are only for synchronization with things React doesn't control.
Key Takeaway: Effects after events are justified only when synchronizing state changes with external systems—not for React-internal logic, which belongs entirely in event handlers.