Categories
React

How to Send Data From Child to Parent Component with React Hooks?

Spread the love

Sending data from a child component to a parent component is an operation that we sometimes want to do.

We can send data from a child component to its parent easily.

In this article,e we’ll look at how to send data from the child component to the parent component with components that are made with React hooks.

Send Data From Child to Parent Component

We can send data from the child component to the parent by passing a function from the parent component to its child as a prop.

Then the child component can call the component from the prop to send the data to the parent.

For instance, we can write:

import { useCallback, useState } from "react";

const Counter = ({ parentCallback }) => {
  const [count, setCount] = useState(0);

  return (
    <button
      onClick={() => {
        setCount((count) => count + 1);
        parentCallback(count + 1);
      }}
    >
      increment
    </button>
  );
};

export default function App() {
  const [count, setCount] = useState(0);

  const callback = useCallback((count) => {
    setCount(count);
  }, []);

  return (
    <div className="App">
      <Counter parentCallback={callback} />
      <h2>count {count}</h2>
    </div>
  );
}

We have the Counter value which takes the parentCallback prop.

We defined the count state which we update when we click on the increment button.

The onClick prop of the button to call setCount with a callback to return the new count value.

Also, we call the parentCallback with count + 1 to send the latest count value to the App component.

In App component, we also have the count state.

And we create a callback with the useCallback hook with the function we want to call.

It returns the callback from the first argument.

The callback calls setCount to update count from the count parameter.

The 2nd argument is the dependencies, which is empty because it doesn’t depend on anything.

Then we call in callback as the value of the parentCallback prop in Counter .

And we see the count below the button.

Conclusion

We pass values from a child component to the parent by passing a function from the parent to the child as a prop.

Then we can call the function with arguments set to the data we want to pass to the parent.

And in the parent component, we can do what we want with the data.

One reply on “How to Send Data From Child to Parent Component with React Hooks?”

Leave a Reply

Your email address will not be published. Required fields are marked *