पाठ 10 / 25
Lifting State Up and Derived Values
One source of truth.
Share by moving state to the common parent
When two components need the same data, move the state to their closest common parent and pass it down as props, with callbacks to change it (lifting state up). Avoid duplicating state in several places, where copies drift apart. Values that can be computed from state or props (a Fahrenheit value from Celsius, a filtered list, a total) should be derived during render, not stored in separate state that must be kept in sync.
One stored value, one derived value, run
I ran this with React 19.3 and react-dom 19.3 on Node.js 22, compiling JSX with esbuild 0.28. Browser-style examples use jsdom 29 as a fake DOM (imported from a small setup-dom.mjs file) and act() to apply updates. The converter stores only Celsius (100) and computes Fahrenheit (212) during render; both inputs and the message stay consistent because there is one source of truth.
import { renderToStaticMarkup } from "react-dom/server";
function TemperatureInput({ label, value }) {
return <label>{label}: <input value={value} readOnly /></label>;
}
function Converter({ celsius }) { // single source of truth lives in the parent
const fahrenheit = (celsius * 9) / 5 + 32; // derived, not stored separately
return (
<div>
<TemperatureInput label="Celsius" value={celsius} />
<TemperatureInput label="Fahrenheit" value={fahrenheit} />
<p>{celsius >= 100 ? "Water boils" : "Water does not boil"}</p>
</div>
);
}
console.log(renderToStaticMarkup(<Converter celsius={100} />));
Output:
<div><label>Celsius: <input readOnly="" value="100"/></label><label>Fahrenheit: <input readOnly="" value="212"/></label><p>Water boils</p></div>
Ask "can this be computed?"
Before adding useState, check whether the value can be derived from existing state or props.
त्वरित जाँच: Two sibling components need the same state. Where should it live?
- In their closest common parent, passed down as props
- Duplicated in both siblings
- In a global variable
- In the DOM
Answer
In their closest common parent, passed down as props — Lift state up.