Sub topic 8
Derive, don't duplicate: the temperature converter
This chapter assumes you can write function components, use useState, pass props and callbacks, and handle onChange. It also assumes you have already lifted state into a common parent. Here you decide what that parent should store and what it should calculate.
The tempting design: two copies
Suppose you build two inputs, Celsius and Fahrenheit, that must always agree. The first idea is to keep two state variables, celsius and fahrenheit. Each change handler then updates both.
This works until one update is missed. You add a third scale, or a handler forgets to update the other variable, and the inputs disagree. Nothing in React tells you which one is right, because you created two sources of truth for one fact.
What to store
Store the smallest state that describes what the user did. The user typed some text into one of the two inputs. That is two facts: the text and which scale it belongs to. Everything else can be calculated from them.
import { useState } from 'react';
function toCelsius(f) {
return ((f - 32) * 5) / 9;
}
function toFahrenheit(c) {
return (c * 9) / 5 + 32;
}
function convert(value, convertFn) {
const input = parseFloat(value);
if (Number.isNaN(input)) return '';
return String(Math.round(convertFn(input) * 100) / 100);
}
function TemperatureInput({ scale, value, onChange }) {
return (
<label>
{scale === 'c' ? 'Celsius' : 'Fahrenheit'}:{' '}
<input value={value} onChange={e => onChange(e.target.value)} />
</label>
);
}
export default function Calculator() {
const [state, setState] = useState({ scale: 'c', value: '' });
const celsius =
state.scale === 'c' ? state.value : convert(state.value, toCelsius);
const fahrenheit =
state.scale === 'f' ? state.value : convert(state.value, toFahrenheit);
return (
<>
<TemperatureInput
scale="c"
value={celsius}
onChange={value => setState({ scale: 'c', value })}
/>
<TemperatureInput
scale="f"
value={fahrenheit}
onChange={value => setState({ scale: 'f', value })}
/>
</>
);
}Calculator owns one state object. The two const lines are not state. They are ordinary variables that React recomputes on every render. Both TemperatureInput components are controlled, so each shows exactly the value it receives.
How a keystroke flows
Say the user types 100 into the Fahrenheit input. The state becomes { scale: 'f', value: '100' }. During the render, fahrenheit is the raw string '100' and celsius is convert('100', toCelsius), which gives '37.78'. No code ever has to "sync" the inputs, because they cannot disagree.
Why keep the raw text
The edited input uses the string the user typed, not a converted number. If you converted and rounded it on every keystroke, typing 1. would be rewritten to 1 and the user could never enter a decimal point. Only the other input shows the converted, rounded value.
This is also why value stays a string. parseFloat returns NaN for empty or invalid text, and convert turns that into ''. The other field simply goes blank instead of showing NaN.
A rule for spotting derived values
Before adding a state variable, ask three questions:
- Can I calculate it from props or other state? If yes, derive it.
- Does it stay the same across renders unless the user acts? If not, it is probably not state.
- Is it passed down unchanged from a parent? If yes, it is a prop, not state.
Common errors
- Copying a prop into state.
useState(props.value)reads the prop only on the first render. Later changes to the prop are ignored. - Syncing state with an effect. Calling
setFahrenheitinsideuseEffectwhencelsiuschanges causes an extra render and a moment where the values disagree. Calculate during render instead. - Storing numbers for text inputs. Parsing on every keystroke breaks partial input such as
-or1.. - Doing expensive work in the derivation. Converting a temperature is cheap. If a derived value is costly, measure it first, then consider
useMemo.
Exercise
You add a Kelvin input to the Calculator. What changes in the state, and what do you add to the render?
Show answer
The state does not change. It still holds the last edited scale and its raw text. You add a toKelvin conversion (for example from Celsius plus 273.15), a kelvin variable derived during render in the same way as the other two, and a third TemperatureInput whose onChange sets { scale: 'k', value }. You also need conversion functions from Kelvin to the other scales.