Coding exercise: build a parent-child communication example in React.
Model answer
Data goes down through props, and events go up through callback props. The parent owns the state, the child only displays it and reports what the user did.
function Parent() {
const [count, setCount] = useState(0);
return (
<>
<p>Parent count: {count}</p>
<Child label="Add one" onPress={() => setCount((c) => c + 1)} />
</>
);
}
function Child({ label, onPress }) {
return <button onClick={onPress}>{label}</button>;
}If two siblings need the same data, lift the state up to their closest common parent. For data needed deep in the tree, use context instead of passing props through every level.
Tips
- Say "props down, events up" in the interview. It is the phrase they listen for.
Practise it yourself in the React and Angular code playground.
Learn this topic
React.js Full Course: Beginner to Advanced .
Sign in to add your own answer.
More questions
- Coding exercise: build a Todo application in React.
- Coding exercise: create a search box with debounce in React.
- Coding exercise: fetch API data and display it in a table in React.
- Coding exercise: implement pagination in React.
- Coding exercise: create a login form with validation in React.
- Coding exercise: implement sorting and filtering in React.