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.

Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro

Recommended