This blog will teach you how parent and child components pass data between themselves in React
To get the most out of this post, it's best if you understand props in React, what a component is, what state is, useState(), useEffect(), and lifting state pattern. It's best if you install create-react-app
This is an important topic because when you've got a parent and child hierarchy of components, the parent will often hold a shared state for the children. The children may trigger events that change the state of the UI, so the parent must update its shared state for the other child components. An example could be a filter search component where selecting the filter changes that state of the UI, and so the results must reflect that change.
Body
Let's look at the filter search component example. If we look at it, we see that we use this concept to pass the state from the parent to the filter and list component using props. When filters are selected, the list component needs to reflect the change => we need the filter to update the shared state parent.
// put code here of FilterSearch component that holds a filter component and list component
// put code for filter component
We need a way to update the state of the parent. We have useState() hook that provides us with setState(). We want to call this whenever we want to update the state. We'll create a onCheckboxClick method in the parent that calls setState().
// update FilterSearch code
We want to pass onCheckboxClick to the filter component as a prop so we can call it in the component
// update filter component
See that now as our filter changes, our list changes too
Conclusion
Now that you've learned about how parent and child components, take a look at useEffect()
Top comments (0)