React · Frontend system thinking
What is useEffect actually for?
Short answer
useEffect synchronizes a component with an external system after rendering, such as a network connection, browser API, timer or third-party widget. It is not for deriving state or handling events.
An effect runs after React commits the DOM update. Its job is to keep something outside React in sync with the current props and state. If the value can be computed during render, compute it during render. If the work happens because the user clicked something, do it in the event handler, not in an effect.
function ChatRoom({ roomId }) {
const [messages, setMessages] = useState([]);
useEffect(() => {
const socket = createSocket(roomId);
const handleMessage = (message) => {
setMessages((current) => [...current, message]);
};
socket.on("message", handleMessage);
return () => {
socket.off("message", handleMessage);
socket.disconnect();
};
}, [roomId]);
return <MessageList messages={messages} />;
}Good reasons to use an effect
- Subscribing to browser events, sockets or stores
- Using a browser API that is not available during server rendering
- Integrating a non-React widget such as a map or video player
- Starting and cancelling work that depends on the committed UI
Data fetching is a common effect use, but it is usually better handled by a router loader, a framework or a data library. Those tools solve race conditions, caching and cancellation that a hand-written effect often gets wrong.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why shouldn't you derive state in an effect?
- 2Should you fetch data inside useEffect?
- 3What is the difference between an effect and an event handler?
- 4Why does StrictMode run effects twice in development?
Say it in the interview
useEffect is for synchronizing with systems outside React after a commit. I use it for subscriptions, browser APIs, timers and third-party widgets. I do not use it to compute values that can be derived during render, or to run code that belongs in an event handler. When I do use it, I keep the setup and cleanup symmetrical so it is safe to run more than once.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live React mock interview and get scored feedback on depth, clarity and confidence.