How to 'Change' a Prop Value
You'll learn: Two patterns for "changing" prop values when props themselves can't be modified.
The Problem
You've learned that props are read-only — you literally can't reassign them. But what if you receive color="blue" as a prop and need to let the user change it to red? You need a workaround.
The Two Solutions
1. Copy Props into Local State
If the parent doesn't need to know about changes, copy the prop value into useState when the component first mounts:
function ColorPicker({ initialColor }) {
const [color, setColor] = useState(initialColor);
return (
<button onClick={() => setColor('red')}>
Current: {color}
</button>
);
}
Now you're modifying state, not props. The prop just provides the starting value.
2. Signal Changes Back to the Parent
If the parent does need to know, the parent passes down a callback function as a prop:
function Parent() {
const [color, setColor] = useState('blue');
return <ColorPicker color={color} onColorChange={setColor} />;
}
function ColorPicker({ color, onColorChange }) {
return (
<button onClick={() => onColorChange('red')}>
Current: {color}
</button>
);
}
The child calls onColorChange to tell the parent "please update this value." The parent updates its state, which flows back down as a new prop value.
Think of It Like This
Props are like parameters in a function call — you can't change them. But you can store them in a local variable (useState) or call another function (onColorChange) to request changes.
Key Takeaway: You never mutate props directly. Instead, copy them into useState for local changes, or call callback props to request the parent update its state.