React
/Intermediate
Child to Parent Communication
Definition
Because React has one-way data flow (downwards), the only way for a child to communicate back up to a parent is for the parent to pass a callback function down to the child as a prop, which the child then executes.
Explain Like I'm New
If the manager (Parent) gives the employee (Child) a clipboard (Props), the employee can't write on it. But, if the manager gives the employee a Walkie-Talkie (a Callback Function), the employee can press the button and talk back to the manager whenever a job is done.
Real World Example
A `<SearchBar>` child component has an input field. When the user clicks "Search", it calls the `onSearchSubmit(query)` function passed down from the `<App>` parent, allowing the parent to fetch the data.
Common Use Cases
- •Form submissions inside child components
- •Triggering modals or UI changes in the parent layout
- •Passing child-generated data back up the tree
Interactive Example
Loading Code Playground...
Interview Questions
basic
- How does a child send data to a parent?
- Does data actually flow "up" in React?
intermediate
- What happens if the child calls a parent callback that calls `setState`?
- How do you pass arguments from the child to the parent's function?
advanced
- Why might passing inline arrow functions as callbacks to children cause performance issues?
- How do you handle multiple deeply nested children passing data up to one parent?
trick
- Can a child directly access the parent's `useState` setter function?