Combining Prop and Local State Correctly
What you'll learn: How to build components that accept external control through props while maintaining their own internal state, without falling into the useEffect synchronization trap.
The Pattern: Two States, Two Purposes
Sometimes a component needs both a prop value and its own internal state. The key is recognizing they serve different purposes and shouldn't be synchronized with useEffect.
Think of it like a thermostat: the manufacturer sets a default temperature (prop), but the homeowner can adjust it (local state). The homeowner's adjustment doesn't need to "sync" with the factory default—it simply starts from it.
Common Scenario: Default Value with User Override
function SearchBox({ defaultQuery = '' }) {
// ❌ WRONG: Using effect to sync prop to state
const [query, setQuery] = useState('');
useEffect(() => {
setQuery(defaultQuery);
}, [defaultQuery]);
// ✅ RIGHT: Initialize once, let user control after
const [query, setQuery] = useState(defaultQuery);
return (
<input
value={query}
onChange={e => setQuery(e.target.value)}
/>
);
}
The Rule: Initialize, Don't Synchronize
The prop provides the initial value. After that, local state takes over completely. No effect needed.
If the parent must control updates, use the key prop to force a reset:
// Parent component
<SearchBox key={userId} defaultQuery={userPreference} />
When userId changes, React unmounts and remounts SearchBox, naturally resetting to the new defaultQuery.
When Both States Coexist
Sometimes you need both the prop value and a modified version:
function PriceInput({ suggestedPrice }) {
const [customPrice, setCustomPrice] = useState('');
const displayPrice = customPrice || suggestedPrice; // Derived, no effect
return <input value={displayPrice} onChange={...} />;
}
Key Takeaway: Props can provide initial or fallback values for local state without useEffect synchronization. Initialize with the prop, let local state evolve independently, and use key for true resets.