CodeNewbie Community 🌱

Unpublished Post. This URL is public but secret, so share at your own discretion.

[DRAFT] How parent and child components pass data in React

Intro

  1. This blog will teach you how parent and child components pass data between themselves in React
  2. 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
  3. 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

  1. 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
Enter fullscreen mode Exit fullscreen mode
// put code for filter component
Enter fullscreen mode Exit fullscreen mode
  1. 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
Enter fullscreen mode Exit fullscreen mode
  1. We want to pass onCheckboxClick to the filter component as a prop so we can call it in the component
// update filter component
Enter fullscreen mode Exit fullscreen mode
  1. See that now as our filter changes, our list changes too

Conclusion

  1. Now that you've learned about how parent and child components, take a look at useEffect()
  2. For more reading, check out lifting state

Top comments (0)