One owner
When two components need the same changing data, do not copy it into both. Move that state to their closest common parent, then pass it down with props.
The parent owns the data. Children display it or ask to change it by calling handler props.
Why lift state
Imagine a project idea filter. One component has the search box. Another component shows matching ideas. If the search text stays inside the search component, the list cannot use it.
So the parent keeps searchText in state. The search box receives value and onChange. The list receives the filtered ideas.
Choose the parent
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done
Before and after
Here, SearchBox should not own the search text if IdeaList also needs it. App is the closest common parent, so App owns searchText.
Notice the direction. Data goes down. Events go up through handler props.
import { useState } from 'react';
const ideas = [
{ id: 'upi-split', title: 'UPI bill splitter' },
{ id: 'mess-menu', title: 'Hostel mess menu tracker' },
{ id: 'notes-share', title: 'Class notes exchange' },
];
export default function App() {
const [searchText, setSearchText] = useState('');
const visibleIdeas = ideas.filter((idea) =>
idea.title.toLowerCase().includes(searchText.toLowerCase())
);
return (
<main>
<h1>Hackathon ideas</h1>
<SearchBox value={searchText} onChange={setSearchText} />
<IdeaList ideas={visibleIdeas} />
</main>
);
}
function SearchBox({ value, onChange }) {
return (
<label>
Search ideas
<input
value={value}
onChange={(event) => onChange(event.target.value)}
placeholder="Try UPI"
/>
</label>
);
}
function IdeaList({ ideas }) {
return (
<ul>
{ideas.map((idea) => (
<li key={idea.id}>{idea.title}</li>
))}
</ul>
);
}Do not sync copies
A common bug is keeping searchText in App and also localText in SearchBox, then trying to keep them equal later. That creates two sources of truth.
For shared state, keep one source. If a value can be computed from current state or props, compute it during render. Do not store it as extra state.
Name handlers clearly
Use prop names that show what the child can request. onChange is fine for an input wrapper. For app actions, use names like onAddIdea, onRemoveIdea, or onSelectIdea.
This makes your repo easier to inspect. A recruiter can see which component owns state and which component only receives props.
Do this now
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done