Catalog My learning Blog
Frontend Developer Course: 100 Concepts in 100 Days · Phase 6 · Lesson 54 · 6 min read

React useEffect Explained: When You Need It

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: A Chat Room Subscription and Two Effects Removed
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Use effects for their real purpose, synchronizing a component with an external system, write correct dependency arrays and cleanup functions, recognize the many cases where an effect is unnecessary, and handle subscriptions, timers and data fetching without leaks or race conditions.

Concept Explanation

Rendering must be pure, but components still need to interact with things outside React: subscribe to a WebSocket, set up a third-party widget, observe element sizes, sync the document title, listen to window events. useEffect is the escape hatch for this. Code inside an effect runs after React has committed the render to the screen. The mental model that avoids most effect bugs is synchronization: an effect keeps an external system in sync with the current props and state, starting synchronization in the setup function and stopping it in the cleanup function it returns.

The dependency array lists every reactive value the effect reads: props, state and anything computed from them. After each render, React compares the dependencies with the previous ones and, if any changed, runs the previous cleanup and then the setup again with the new values. An empty array means the effect only depends on values that never change, so it runs once after the component mounts and cleans up when it unmounts. Leaving out a dependency to stop an effect from rerunning creates a stale closure (Day 33); the right fix is to change the code so the value is not needed, not to lie about dependencies. The react-hooks lint rule checks this.

Cleanup is not optional. A subscription without an unsubscribe, an interval without a clear, or a listener without removal keeps running after the component is gone, causing leaks and updates to unmounted components. In development, React's Strict Mode deliberately mounts, unmounts and remounts each component once, running setup, cleanup and setup again, to reveal effects that do not clean up properly. If that double run breaks something, the effect is missing a cleanup.

Many effects should not exist. Transforming data for rendering does not need an effect; compute it during render, memoized if expensive. Responding to a user event belongs in the event handler, not in an effect that watches state changed by the handler. Resetting state when a prop changes is better done with a key on the component. Chains of effects that set state, which triggers another effect, cause extra renders and tangled logic. The React documentation's article "You Might Not Need an Effect" catalogs these cases, and following it removes a large share of bugs in typical codebases.

Data fetching in effects is possible but subtle: you need to handle loading and error states, ignore or abort stale responses when inputs change quickly, avoid waterfalls and cache results. That is why most applications use a data library or a framework loader instead (Days 62 and 63). When you must fetch in an effect, abort the request in the cleanup, as Day 37 described, so a stale response can never overwrite a newer one.

SituationUse an effect?Better approach
Subscribe to an external store or socketYesSetup subscribes, cleanup unsubscribes
Integrate a non-React widgetYesCreate in setup, destroy in cleanup
Sync document title or a third-party SDKYesDepend on the values being synced
Compute filtered or sorted dataNoDerive during render, memoize if slow
React to a button clickNoDo it in the event handler
Reset state when an id changesNoGive the component key={id}
Fetch dataRarelyData library or framework loader
Notify parent of state changeNoCall the parent's callback in the handler

Worked Example: A Chat Room Subscription and Two Effects Removed

The first effect synchronizes with an external connection and cleans up correctly. The next two show effects that should not exist and their replacements.

JavaScript
function ChatRoom({ roomId, serverUrl }) {
  const [messages, setMessages] = useState([]);

  // Correct: synchronize the connection with roomId and serverUrl
  useEffect(() => {
    const conn = createConnection(serverUrl, roomId);
    conn.on('message', (m) => setMessages((prev) => [...prev, m]));   // updater: no stale state
    conn.connect();
    return () => conn.disconnect();                                    // stop syncing the old room
  }, [roomId, serverUrl]);                                             // every reactive value read

  return <MessageList messages={messages} />;
}

// Unnecessary effect 1: derived data stored in state
function ProductList({ products, query }) {
  // const [visible, setVisible] = useState([]);
  // useEffect(() => { setVisible(products.filter(...)) }, [products, query]);  // extra render
  const visible = useMemo(
    () => products.filter((p) => p.name.toLowerCase().includes(query.toLowerCase())),
    [products, query],
  );
  return <Grid items={visible} />;
}

// Unnecessary effect 2: resetting state when a prop changes
function ProfilePage({ userId }) {
  return <ProfileForm key={userId} userId={userId} />;   // new key, fresh state, no effect needed
}

// Window events: subscribe in an effect, or use useSyncExternalStore
function useOnlineStatus() {
  return useSyncExternalStore(
    (cb) => {
      window.addEventListener('online', cb);
      window.addEventListener('offline', cb);
      return () => { window.removeEventListener('online', cb); window.removeEventListener('offline', cb); };
    },
    () => navigator.onLine,
    () => true,                                                         // server snapshot
  );
}

Switching rooms disconnects from the old room before connecting to the new one, because the cleanup from the previous render runs before the next setup. In Strict Mode development you will see connect, disconnect, connect on mount, which confirms the cleanup is correct.

After the first commit the effect connects to room A. When roomId changes, React runs the old cleanup, disconnecting from A, then runs setup for B. On unmount the last cleanup runs. Strict Mode runs setup, cleanup, setup once in development to test this.
After the first commit the effect connects to room A. When roomId changes, React runs the old cleanup, disconnecting from A, then runs setup for B. On unmount the last cleanup runs. Strict Mode runs setup, cleanup, setup once in development to test this.

Real-World Examples

  • The React documentation's article "You Might Not Need an Effect" lists common unnecessary effects, such as transforming data for rendering, handling user events and chaining state updates, and it was written after the team observed these patterns causing bugs and extra renders in many codebases.
  • React 18's Strict Mode began intentionally running effects twice in development, mount, unmount and mount again, and the React team explained that this surfaces missing cleanup logic that would otherwise break features such as fast refresh and future capabilities that preserve state while components are hidden.
Key TakeawaysReact effects synchronize a component with an external system: setup starts synchronizing, and cleanup stops it when values change or it unmounts. The dependency array must list every reactive value the effect reads. Always clean up subscriptions, timers and listeners, and treat Strict Mode's double run as a test. Do not use effects for derived data, user events or resetting state, and prefer data libraries or loaders for fetching.

Review Questions & Answers

Synchronization. The setup function makes an external system match the current props and state, and the cleanup undoes it. When dependencies change, React cleans up the old synchronization and starts a new one with the latest values.

The effect would keep reading values from the render in which it was created, a stale closure, so it works with outdated data. The fix is to restructure the code, for example with an updater function or by moving logic, so the value is genuinely not needed.

To verify that every effect cleans up correctly. Running setup, cleanup and setup again exposes effects that leak subscriptions or depend on running only once, problems that would otherwise appear later with fast refresh or state-preserving features.

Filtering or sorting data for display should be computed during render instead of stored by an effect, and reacting to a user action such as a form submit should happen in the event handler instead of in an effect that watches state set by that handler.