Derived State in React
Derived State in React
function TemperatureConverter() {
const [celsius, setCelsius] = useState(0);
const [fahrenheit, setFahrenheit] = useState(32);
return (
<div>
<label>Celsius:</label>
<input
type="number"
value={celsius}
onChange={(e) => setCelsius(Number(e.target.value))}
/>
<label>Fahrenheit:</label>
<input
type="number"
value={fahrenheit}
onChange={(e) => setFahrenheit(Number(e.target.value))}
/>
</div>
);
}
When the celsius state changes, we calculate fahrenheit based on the formula
(celsius * 9/5) + 32.
When the fahrenheit state changes, we calculate celsius based on the reverse
formula (fahrenheit - 32) * 5/9.
By deriving fahrenheit from celsius and vice versa, we ensure that the two
temperature values are always consistent with each other, and we avoid storing
redundant data.
Derived state is particularly useful when you want to maintain a relationship between
different pieces of data in your component's state without introducing unnecessary
complexity. It allows you to keep your state clean and update only what's necessary,
improving the efficiency of your React components.