Unnecessary effect

2 snippets in React

REReact

When NOT to Use useEffect

RE · useEffect
syntax
// Derived state: compute during render
const fullName = firstName + ' ' + lastName;

// Event response: handle in the event handler
function handleClick() { doSomething(); }
example
// BAD: useEffect to sync derived data
const [firstName, setFirstName] = useState('Kai');
const [lastName, setLastName] = useState('Chen');
const [fullName, setFullName] = useState('');

useEffect(() => {
  setFullName(firstName + ' ' + lastName);
}, [firstName, lastName]);

// GOOD: compute directly during render
const fullName = firstName + ' ' + lastName;

// BAD: useEffect for event-driven logic
useEffect(() => {
  if (submitted) sendAnalytics();
}, [submitted]);

// GOOD: call directly in the event handler
function handleSubmit() {
  submitForm();
  sendAnalytics();
}

Note Overusing useEffect is one of the most common React mistakes. If you can calculate something from existing props or state, do it during render. If something should happen in response to a user action, put it in the event handler.

Overusing useEffect

RE · Common Mistakes
syntax
// ANTI-PATTERN: effect to sync derived state
useEffect(() => { setB(computeFrom(a)); }, [a]);

// BETTER: compute inline
const b = computeFrom(a);
example
// BAD: useEffect chain
function PriceCalculator({ items }) {
  const [subtotal, setSubtotal] = useState(0);
  const [tax, setTax] = useState(0);
  const [total, setTotal] = useState(0);

  useEffect(() => {
    setSubtotal(items.reduce((s, i) => s + i.price, 0));
  }, [items]);

  useEffect(() => {
    setTax(subtotal * 0.1);
  }, [subtotal]);

  useEffect(() => {
    setTotal(subtotal + tax);
  }, [subtotal, tax]);
  // 3 extra renders for what should be 0!

  return <p>Total: ${total.toFixed(2)}</p>;
}

// GOOD: calculate everything inline
function PriceCalculator({ items }) {
  const subtotal = items.reduce((s, i) => s + i.price, 0);
  const tax = subtotal * 0.1;
  const total = subtotal + tax;

  return <p>Total: ${total.toFixed(2)}</p>;
}

Note Each unnecessary useEffect + setState causes an extra render cycle. If a value can be derived from props or state, compute it during render. Reserve useEffect for genuine side effects: API calls, subscriptions, DOM manipulation, and third-party library integration.