Lifting State Up & Passing Data Back to Parent

Can child component send data back to the parent?
✅ The answer: You pass a function from the parent to the child.

🧠 Real-Life Example

Let’s say:

  • You have a parent component that tracks a counter.
  • The child has a button that should increase that counter.

The child can’t change the parent’s state directly,
but it can call a function that the parent gives it.

✅ 9.1 Step-by-Step Example

🧱 Parent Component – Owns the state

import { useState } from "react";
import ChildButton from "./ChildButton";

function Parent() {
  const [count, setCount] = useState(0);

  const handleIncrease = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <h2>Parent Count: {count}</h2>
      <ChildButton onIncrease={handleIncrease} />
    </div>
  );
}

export default Parent;

👶 Child Component – Calls the function

function ChildButton({ onIncrease }) {
  return <button onClick={onIncrease}>Increase Count</button>;
}

export default ChildButton;

🔍 What’s Happening?

  • Parent owns the count state.
  • Parent passes a function (handleIncrease) to child via prop onIncrease.
  • Child calls the function when the button is clicked.
  • Result: Parent updates the state.

✅ 9.2 You Can Also Pass Data to Parent

function Child({ onSend }) {
  return (
    <button onClick={() => onSend("Hello from Child")}>
      Send Message
    </button>
  );
}

In parent:

<Child onSend={(msg) => console.log(msg)} />

✅ Output: "Hello from Child"

Keep Learning 🙂

Leave a Reply

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