Course contentsShow
← React
Lesson 1211 of 2,39631. Forms in ReactFree lesson

Computed Values in Form State

Deriving totals, formatted displays, or conditional field visibility from existing state without storing redundantly.

Computed Values in Form State

What you'll learn: How to derive values like totals, formatted text, or conditional visibility from your form state without creating redundant copies that can fall out of sync.


The Core Idea

When building forms, you often need values that depend on other fields—like a total price, a formatted phone number display, or whether a "shipping address" section should appear. The temptation is to store these in state alongside your actual form data, but this creates a maintenance nightmare: now you have two sources of truth that can drift apart.

Instead, compute these values during render.

Think of it like a spreadsheet: you don't store the result of =A1+A2 in a separate cell and manually update it every time A1 or A2 changes. You write the formula once, and it recalculates automatically. React works the same way.

How It Works in Practice

function OrderForm() {
  const [formData, setFormData] = useState({
    quantity: 1,
    pricePerItem: 29.99,
    taxRate: 0.08
  });

  // ✅ Computed during render
  const subtotal = formData.quantity * formData.pricePerItem;
  const tax = subtotal * formData.taxRate;
  const total = subtotal + tax;
  const showTaxBreakdown = subtotal > 100;

  return (
    <form>
      {/* Use computed values directly */}
      <p>Subtotal: ${subtotal.toFixed(2)}</p>
      {showTaxBreakdown && <p>Tax: ${tax.toFixed(2)}</p>}
      <p>Total: ${total.toFixed(2)}</p>
    </form>
  );
}

The subtotal, tax, total, and showTaxBreakdown aren't in state—they're calculated fresh on every render from the actual source data. This means they're always correct and you never have to remember to update them.

Key Takeaway: Don't store derived or computed values in form state—calculate them during render from your single source of truth. This eliminates sync bugs and keeps your state minimal.