Sub topic 8
Derive, don't duplicate: the temperature converter
This chapter assumes you can write function components, use useState, and pass props and callbacks down. It also assumes you have seen the previous chapters' pattern of lifting state into a common parent. Here the question is what that parent should store. The answer is the smallest amount of state that describes the situation. Everything else is computed during render.
The goal: two inputs, one temperature
A temperature converter has two inputs, Celsius and Fahrenheit. Typing in either one must update the other. Lifting state up tells you that the parent, Calculator, owns the value. That leaves a design choice.
The obvious design keeps two pieces of state, one per input. Each handler converts the new value and writes both. The sketch below shows it with the helpers inlined so it runs as written.
import { useState } from 'react';
const toF = c => String((parseFloat(c) * 9) / 5 + 32);
const toC = f => String(((parseFloat(f) - 32) * 5) / 9);
export default function DuplicatedCalculator() {
const [celsius, setCelsius] = useState('');
const [fahrenheit, setFahrenheit] = useState('');
function handleCelsius(value) {
setCelsius(value);
setFahrenheit(value === '' ? '' : toF(value));
}
function handleFahrenheit(value) {
setFahrenheit(value);
setCelsius(value === '' ? '' : toC(value));
}
return (
<>
<label>
Celsius:{' '}
<input value={celsius} onChange={e => handleCelsius(e.target.value)} />
</label>
<label>
Fahrenheit:{' '}
<input
value={fahrenheit}
onChange={e => handleFahrenheit(e.target.value)}
/>
</label>
</>
);
}This works in the happy path, but it has the same flaw as the sibling problem from earlier in this tutorial, only inside one component. There are two copies of one fact. Every code path that changes one copy must remember to change the other. Nothing enforces that. If you later add a "Reset to freezing" button and forget to call both setters, the inputs disagree.
It also has visible bugs. Typing abc makes toF return the string "NaN", which then appears in the other input. Typing 36. in Celsius immediately rewrites the Fahrenheit field with a long unrounded decimal such as 96.80000000000001. The inputs can also fight each other. If a later change makes the Fahrenheit write trigger a Celsius write, the value rewrites itself.
What is the minimal state?
Ask what the user actually told you. They typed one string into one input. That is two facts: which scale they edited and what they typed. The other field is a function of those two facts. It is not a separate fact.
So the state is one object with two fields:
scale:'c'or'f', the input that was edited last.value: the raw string exactly as typed.
Storing the raw string, not a parsed number, matters. A parsed number loses what the user typed. "3." and "3.0" and "03" all parse to 3. If you wrote the parsed number back into the input, the field would rewrite itself mid-keystroke and the user could never type a decimal point.
The full solution
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 })}
/>
</>
);
}Reading it top to bottom
toCelsius and toFahrenheit are pure functions. They take a number and return a number, with no state and no side effects, so you can test them on their own.
convert wraps them for use with raw strings. It parses the text and returns an empty string if the text is not a number. Otherwise it applies the conversion and rounds to two decimals. Returning '' for bad input is what stops "NaN" from appearing in the other field.
TemperatureInput is a controlled component. It holds no state. It shows the value it receives and reports every change through onChange. It passes the new string up, not the event object, so the parent never needs to know about DOM events.
Calculator owns the state and computes both display values on every render. For the input the user is editing, it uses the raw string. For the other input, it converts that string. That asymmetry is deliberate. The edited field must show exactly what was typed, while the other field is allowed to be a rounded, formatted result.
How data flows
Data goes up as a callback call and comes down as props. At no point does one input talk to the other. They are connected only through the state in Calculator.
Why derived values cannot drift
When a value is computed during render, it is correct by construction. There is no moment when celsius and fahrenheit disagree, because both come from the same state in the same render. A bug elsewhere cannot leave them out of sync, because there is nothing to forget to update.
Compare this with the duplicated version. Adding a reset button there means touching two setters. Here it is one call:
<button onClick={() => setState({ scale: 'c', value: '' })}>Reset</button>This is the practical meaning of the single-source-of-truth idea from the previous chapter. State should have one writer path, and anything that can be calculated from it should be calculated.
A rule of thumb for deriving
Before adding useState, ask three questions about a candidate value:
- Can it be computed from props or from other state? If yes, derive it.
- Does it stay unchanged over time? If yes, it is a constant, not state.
- Is it passed in from a parent? If yes, it is a prop. Copying a prop into state means later changes to the prop are ignored.
Only a value that fails all three belongs in state.
Edge cases
| Input | Behavior | Reason |
|---|---|---|
| Empty string | Both inputs empty | `parseFloat('')` is `NaN`, so `convert` returns `''` |
| `abc` | Edited field shows `abc`, other field empty | The raw text is kept, and `convert` rejects it |
| `36.` | Edited field keeps the dot, other field shows the converted `36` | The raw string is stored, so the dot is not removed while typing |
| `12abc` | Other field converts `12` | `parseFloat` reads the leading number and ignores the rest |
| `-` | Other field empty | A lone minus sign parses as `NaN` |
| `36.6` in Celsius | Fahrenheit shows `97.88` | The rounding to two decimals happens only on the derived side |
The 12abc row is a trade-off. parseFloat is lenient. If you want stricter input, use Number(value) and also reject the empty string, because Number('') is 0. Either way, the rule stays the same: keep what the user typed, and put validation in the derivation.
Common errors in this pattern
- Storing the number instead of the string.
setState({ scale, value: parseFloat(text) })makes decimals and minus signs impossible to type, since the input rewrites itself after each keystroke. - Forgetting the scale. If you store only
value, you cannot tell which input the number came from, so both fields would show the same number. - Calling
convertin the edited field too. Round-tripping the user's own text through a conversion and back changes what they typed. - Mutating state. Write
setState({ scale: 'c', value }). Do not writestate.value = value. React compares the old and new object by reference, so a mutated object does not trigger a render. - Passing a handler that expects an event.
TemperatureInputcallsonChange(e.target.value)with a string. If the parent handler expectse.target.valueagain, it will readundefined.
Exercise
Add a third input for Kelvin to Calculator. Kelvin equals Celsius plus 273.15. List what changes in the state shape and what changes in the render body.
Show answer
The state shape does not change. { scale, value } still describes what the user typed, with 'k' as a third possible scale. Add toKelvin and fromKelvin helper functions, a Kelvin branch in TemperatureInput's label, and compute kelvin in the render body as state.scale === 'k' ? state.value : convert(state.value, ...). The other two derived values also need a Kelvin case, for example by converting from Kelvin to Celsius first. Add a third <TemperatureInput scale="k" ... /> whose onChange calls setState({ scale: 'k', value }). No third piece of state is needed.
Exercise
A teammate replaces the state with useState({ scale: 'c', value: 0 }) and stores parseFloat(text) in value. What goes wrong when a user tries to type 5.5 into the Celsius field, and why?
Show answer
After typing 5 and then ., the text is "5.", which parses to 5. The parent stores 5 and renders 5 back into the input, so the dot disappears and the user cannot type a decimal. The fix is to store the raw string and parse only inside convert.
Exercise
Which of these should be state, and which should be derived? (a) the Fahrenheit value while the user edits Celsius, (b) the text in the field being edited, (c) whether the Celsius value is below freezing.
Show answer
(a) is derived, because it is computed from scale and value. (b) is state, because it is the user's raw input and cannot be computed from anything else. (c) is derived, because it can be computed in the render body, for example parseFloat(celsius) < 0.