← Back to Chapters

Derived State

⚛️ Derived State

React • Derived State • Hooks

⚡ Quick Overview

Derived state is state that is computed from props or user input instead of being stored independently.

It helps keep the UI consistent with incoming data, but if used incorrectly it can cause unnecessary re-renders, duplicated state, or stale values.

Use derived state when a component needs to respond to changes in props or related user inputs, while still keeping the logic predictable and easy to understand.

? Key Concepts

  • Derived state is not original data — it is computed from existing props or state.
  • Avoid copying props directly into state unless you plan to modify them locally.
  • If a value can be computed every render without performance issues, you usually don’t need state for it.
  • Use useEffect to sync derived state only when necessary (e.g., when props change).
  • Keep derived calculations pure — do not mutate props or unrelated state inside them.
  • For heavy calculations, use useMemo() to cache derived values.

? Example: Deriving State from Props

Imagine a parent passes a price prop, and the child needs to display the price including tax (for example, 18% GST).

? View Code Example
// React component that derives final price (with tax) from a price prop
function PriceDisplay({ price }) {
const [finalPrice, setFinalPrice] = React.useState(price * 1.18);
React.useEffect(() => {
setFinalPrice(price * 1.18); // Update derived state whenever the price prop changes
}, [price]);
return <h3>Final Price: ₹{finalPrice.toFixed(2)}</h3>;
}

? Live Output / Explanation

If the parent passes price = 1000, the component will compute:

  • finalPrice = 1000 * 1.18 = 1180
  • The UI will render: Final Price: ₹1180.00

If later the parent updates price to 1500, the useEffect runs again and recomputes finalPrice using the latest prop.

? Compute Inside Render vs. Store in State

In many cases, you don’t need separate state for derived values. You can calculate them directly inside the render function.

? View Code Example
// Simpler version: derive finalPrice directly during render
function PriceDisplay({ price }) {
const finalPrice = price * 1.18;
return <h3>Final Price: ₹{finalPrice.toFixed(2)}</h3>;
}

? Explanation

This approach is enough when:

  • You don’t need to edit the derived value locally.
  • The calculation is cheap and can run on every render.

Only store derived values in state if you plan to let the user modify them or you must reuse them across multiple renders in a way that can’t be recomputed easily.

? Derived State from User Input

You can also derive state based on user actions, like keeping two related inputs (Celsius and Fahrenheit) in sync.

? View Code Example
// Temperature converter that derives Fahrenheit from the Celsius input
function TemperatureConverter() {
const [celsius, setCelsius] = React.useState(0);
const [fahrenheit, setFahrenheit] = React.useState(32);
const handleCelsiusChange = (e) => {
const c = e.target.value;
setCelsius(c);
setFahrenheit((c * 9) / 5 + 32); // Derive Fahrenheit from the updated Celsius value
};
return (
<div>
<input type="number" value={celsius} onChange={handleCelsiusChange} />
<p>Fahrenheit: {fahrenheit}</p>
</div>
);
}

?️ Live Output / Explanation

When the user types 0 in the Celsius input, Fahrenheit shows 32. If the user types 100, the displayed Fahrenheit becomes 212.

The key idea: fahrenheit is always derived from the current celsius value.

?️ Example: Syncing Props and Editable Input

Sometimes you want to:

  • Start with a value passed from the parent via props.
  • Let the user edit it locally.
  • Still react if the parent later changes the prop.
? View Code Example
// Editable title that stays in sync with the parent prop
function EditableTitle({ title }) {
const [text, setText] = React.useState(title);
React.useEffect(() => {
setText(title); // Refresh local state whenever the title prop changes
}, [title]);
return (
<div>
<input value={text} onChange={(e) => setText(e.target.value)} />
<p>Preview: {text}</p>
</div>
);
}

? Live Output / Explanation

The user can freely edit the input, and the preview updates immediately.

If the parent sends a new title prop (for example, after loading data), the useEffect hook will sync the local text state with the new title.

? When Should You Use Derived State?

  • ✅ When the child needs to modify a prop locally (e.g., form fields based on initial data).
  • ✅ When an expensive calculation depends on props and you want to memoize/cache it.
  • ✅ When you must keep local state synchronized with changing props.
  • ❌ Avoid derived state if you can compute the value directly during render.
  • ❌ Don’t store the same information in two places (props + state) unless you have a clear reason.

? Tips & Best Practices

  • Prefer calculating values directly from props instead of duplicating them in state.
  • When using derived state, always synchronize it in useEffect with a clear dependency array.
  • Keep derived state minimal — unnecessary duplication makes components harder to debug.
  • For performance-heavy calculations, use useMemo() to avoid recalculating on every render.
  • Make sure derived logic is pure — given the same inputs, it should always produce the same output.

? Try It Yourself

  1. Create a component that takes a prop basePrice and displays the final price after a 10% discount.
  2. Modify the component so it automatically recomputes whenever basePrice changes from the parent.
  3. Build a bi-directional temperature converter (Celsius ↔ Fahrenheit) using derived values.
  4. Try syncing an editable input with a prop like defaultText using useEffect.

Goal: Get comfortable creating and managing derived state from props or user input while keeping React components predictable and efficient.