Derived state

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.

Derived State

RE · State Management
syntax
// Compute from existing state during render
const derivedValue = computeFrom(stateA, stateB);
// Do NOT store derived values in separate state
example
function ShoppingCart({ items }) {
  // GOOD: derive during render
  const subtotal = items.reduce((sum, item) => sum + item.price * item.qty, 0);
  const tax = subtotal * 0.08;
  const total = subtotal + tax;
  const itemCount = items.reduce((sum, item) => sum + item.qty, 0);

  return (
    <div>
      <p>{itemCount} items</p>
      <p>Subtotal: ${subtotal.toFixed(2)}</p>
      <p>Tax: ${tax.toFixed(2)}</p>
      <p>Total: ${total.toFixed(2)}</p>
    </div>
  );

  // BAD: storing derived data in state
  // const [total, setTotal] = useState(0);
  // useEffect(() => setTotal(subtotal + tax), [subtotal, tax]);
}

Note If you can compute a value from existing state or props, derive it inline during render instead of syncing it with useState + useEffect. Derived state in useEffect causes an extra render cycle and introduces potential bugs.