How to Easily Pass Data From Child to Parent in React
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>
)
}
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>
)
}
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.

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 less time.
Learn MoreRecommended

How to Save Writable Store in Svelte to Local Storage
Learn how to create a persistent store in Svelte

How to Create an Infinite Scroll Component in React
With the help of the Intersection Observer API
