How to Easily Pass Data From Child to Parent in React

Ferenc Almasi • 2022 September 13 • 📖 3 min read

To easily pass data from your child to the parent component in React, pass a callback function to your child as a prop, call the function inside your child with your data, and access the data within your function from your parent component. This looks like the following in terms of code:

import { useState } from 'react'

const Child = ({ callback }) => {
    const state = {
        example: '👋'
    }

    const handleCallback = () => callback(state)

    return (
        <button onClick={handleCallback}>Pass data to parent</button>
    )
}

export default function Parent() {
    const [state, setState] = useState({})
    const callback = payload => {
        setState(payload)

        console.log(state)
    }

    return (
        <div>
            <h1>Hello from Parent</h1>
            <Child callback={callback} />
        </div>
    )
}
Copied to clipboard!

First, we created an empty state inside the parent component using the useState hook. Then we called the Child component with a callback prop, passing it a function that we defined inside our parent.

Notice that we use setState to set the state to the payload of the function. This function will be called from within our Child component, and it will be responsible for passing the correct data. Let's take a look at the child component now.

const Child = ({ callback }) => {
    const state = {
        example: '👋'
    }
    
    // Here we are setting the payload for the callback inside the Parent
    const handleCallback = () => callback(state)

    return (
        <button onClick={handleCallback}>Pass data to parent</button>
    )
}
Copied to clipboard!

Inside the child, we destructure the props so that we can grab callback right away, then call it with the internal state using an onClick handler. This state object will be the value of the payload that we receive inside our Parent component.

This way, you can pass any data you need from your Child component to your Parent using a callback function. And by using a useState hook inside the parent, we can also access the passed state outside of the callback function.

JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in 5 hours.

Learn More

📚 Get access to exclusive content

Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. ☕

Get access Support us
Read more on
🎉 Thank you for subscribing to our newsletter. x