Initial State from Props
What you'll learn: How to initialize a component's state using a value passed in through props — and why this only happens once.
The Core Idea
Sometimes you want a component to start with state that comes from its parent. You might receive a defaultValue or initialCount prop and use it to set up your useState initial value:
function Counter({ startingCount }) {
const [count, setCount] = useState(startingCount);
// ...
}
This looks straightforward, but here's the crucial detail: the prop is only read during the component's first render. If the parent changes startingCount later, your component's state won't update — the state has already been initialized.
Why It Only Happens Once
Think of it like filling a glass with water. The prop tells you how much water to start with, but once the glass is filled, changing the label on the bottle doesn't change what's already in the glass.
Initial state runs only once per component instance (as you learned in lesson 354). React reads startingCount when the component mounts, sets the state, and from that point forward, the state belongs to the component. The prop's job is done.
Common Use Case
function EditableField({ initialText }) {
const [text, setText] = useState(initialText);
return (
<input
value={text}
onChange={(e) => setText(e.target.value)}
/>
);
}
The parent provides the starting text, but once the user starts typing, the component owns that state.
Key Takeaway: Props can initialize state, but they only do so once when the component first mounts — subsequent prop changes won't update existing state.