SmartCodingTips

🔁 Callback Props

Callback props are functions passed from a parent component to a child. They let the child notify the parent when something happens — like a button click or input change.


📥 Why Use Callback Props?

  • Enable child-to-parent communication
  • Keep the state and logic in the parent, while the child handles UI
  • Maintain unidirectional data flow

🧠 Example

Here's how a child component sends data back to the parent using a callback function:

// Parent Component
function Parent() {
  const handleMessage = (msg) => {
    alert("Child says: " + msg);
  };

  return <Child onSend={handleMessage} />;
}

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

💡 Tip

You can also use callback props to update parent state based on input from children — commonly used in forms, modals, and custom inputs.


📋 Summary

  • Callback props are functions passed to children
  • Used for triggering actions in the parent
  • Great for keeping logic centralized