React Interview Question: Props vs State and Lifting State Up
Short answer: props are inputs passed from a parent; a component can't change them. State is data a component owns and updates over time, which triggers a re-render.
function Counter({ step }) { // step is a prop
const [count, setCount] = useState(0); // count is state
return <button onClick={() => setCount(count + step)}>{count}</button>;
}
<Counter step={5} />
One-way data flow
Data flows down through props; changes flow up through callbacks. A child asks the parent to change something by calling a function the parent passed in.
Lifting state up
When two siblings need the same data, move the state to their closest common parent and pass it down:
function TemperatureConverter() {
const [celsius, setCelsius] = useState(25); // lifted to the parent
return (
<>
<CelsiusInput value={celsius} onChange={setCelsius} />
<FahrenheitInput
value={celsius * 9 / 5 + 32}
onChange={(f) => setCelsius((f - 32) * 5 / 9)}
/>
</>
);
}
There's now a single source of truth, and both inputs always agree.
Rules of thumb
- Keep state as close as possible to where it's used; lift only when needed.
- Don't copy props into state (
useState(props.value)) unless you deliberately want an initial value that then diverges. - Derive values instead of storing them: if it can be computed from props or state, compute it.
- When lifting goes through many levels, consider composition or context.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.