Coding exercise: build a parent-child communication example in React.

React practical coding · Freshers

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

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