← Back to React, page 6

react-0119 · Medium mid

When should logic go in an event handler instead of useEffect, and what are the common "you might not need an effect" cases?

Effects are for synchronizing with things outside React that must happen because the component is on screen. If the logic is a response to something the user did, put it in the event handler. If a value can be calculated from props and state, calculate it during render. Effects that only update state from other state cause extra renders and bugs. Keep effects for subscriptions, timers, network synchronization and similar external work.

Full answer

The React docs have a whole page on this, and interviewers like to ask for examples. The rule of thumb: an effect describes what to synchronize with the outside world, while an event handler describes what to do when the user does something.

Cases where an effect is not needed:

  1. Derived data. useEffect(() => setFullName(first + ' ' + last), [first, last]) renders twice per change, first with a stale value. Compute const fullName = first + ' ' + last during render, and use useMemo only if the calculation is expensive.
  2. Resetting state when a prop changes. Instead of an effect that calls setComment('') on userId change, give the component a key: <Profile key={userId} />, which makes React create a fresh instance.
  3. Responding to a user action. Showing a toast after "Add to cart", sending a POST request after submit, or navigating after saving all belong in the click or submit handler. Putting them in an effect that watches cart re-fires whenever the dependency changes for any reason (including reload or navigation back).
  4. Chains of effects. One effect sets state which triggers another effect and so on. Calculate everything in the handler or during render.
  5. Notifying parents. Instead of an effect calling onChange(value) when state changes, call onChange in the same handler that updates state, so both updates are batched.
  6. Initializing the app (once). Code that must run once per page load, not per component mount, can go at module level or in an entry file. Strict Mode runs effects twice in development, which exposes this issue.
  7. Subscribing to external stores. Use useSyncExternalStore, not an effect with state.

Cases where an effect is right: synchronizing with a network connection, a timer, a browser API such as the document title or a map widget, analytics events for displaying a screen (page view), and fetching data when no data library or framework handles it.

A good test: "Why does this code run?" If the answer is "because the user clicked", use a handler. If "because the component is shown or a value it displays changed and I must sync with an external system", use an effect.

The example puts the cart logic in the handler and calculates the total in render.

jsx
import { useState } from 'react';

const PRICES = { Pen: 20, Book: 150 };

export default function Cart() {
  const [items, setItems] = useState([]);
  const [toast, setToast] = useState('');

  // Derived during render: no extra state, no effect.
  const total = items.reduce((sum, name) => sum + PRICES[name], 0);

  function addItem(name) {
    setItems([...items, name]);
    // A response to the user's click belongs in the handler, not in an effect that watches items.
    setToast(name + ' added');
    console.log('toast: ' + name + ' added');
  }

  return (
    <div>
      <button onClick={() => addItem('Pen')}>Add Pen</button>
      <button onClick={() => addItem('Book')}>Add Book</button>
      <p>
        {items.length} items, total {total}
      </p>
      <output>{toast}</output>
    </div>
  );
}

The check added a pen twice and a book once. Each toast is created exactly once, in the click that caused it, and the total is always consistent with the items because it is not separate state. Output of the run: toast: Pen added toast: Pen added toast: Book added summary: 3 items, total 190

Key points

  • Handlers respond to user actions. Effects synchronize with external systems.
  • Calculate derived values during render instead of storing them with an effect.
  • Reset state with a key instead of an effect watching a prop.
  • Avoid effect chains and effects that only notify parents. Update everything in one handler.
  • Use effects for subscriptions, timers, network and browser API synchronization.

Common mistakes

  • Using an effect to copy props or state into other state.
  • Running a POST request in an effect that watches form data instead of in the submit handler.
  • Chaining several effects that each set state for the next one.
  • Calling onChange from an effect, which creates an extra render pass.
  • Using effects for one-time app initialization and then seeing it run twice in development.

Follow-ups

  • How does a key help reset state without an effect?
  • When is fetching data in an effect still reasonable?
  • Why does an effect that notifies the parent cause an extra render?

Tips

  • Use the question "why does this code run?". It is a memorable test.
  • List three cases without effects: derived data, reset with key, user actions.
  • Say what effects are good for, so you do not sound against them.