Pass data from child to parent with React Hooks

02 December, 2019
Back

TLDR: Parent passes a callback function through a prop to Child - like a microphone, and Child speaks back by modifying the prop.

parent-and-child

It's always good to listen to your child.

@unsplash

You can do it with 4 steps:

  1. Create a callback function in the Parent component.

This is the most important step. The callback is created in the Parent, not the Child. A callback is basically a function that fires after another completes - in this case, it will wait for Child's sendData() to fire first.

Notice that the callback does something. setData(x) updates the Parent's state from whatever's going to come in from the Child.

  1. Pass the callback function as a prop to Child component.

You're not just passing data as a prop. This time, the whole callback function is a prop.

<Child childProp={callback} />

  1. Modify the state in Child.

There's another function in Child. This is where the magic happens. The Child speaks to the Parent and says, 'I want candy!'. childProp is the means by which they communicate - the microphone.

  1. Render it back at the Parent.

Remember the setData earlier? It modified data to whatever came in from Child.

Here's the code.

import React, { useState } from "react"

const Child = ({ childProp }) => {
  const sendData = () => {
    childProp("I want candy!")
  }
  sendData()
  return <p>I'm the child!</p>
}

const Parent = () => {
  const [data, setData] = useState()
  const callback = x => {
    setData(x)
  }

  return (
    <div>
      <p>I'm the parent.</p>
      <Child childProp={callback} />
      {data}
    </div>
  )
}

export default Parent

And that's how we pass data from Child to Parent.


Back