🔹 What are Callback Functions in React?
A callback function in React is a function passed from parent to child as a prop so that the child can communicate back or trigger logic in the parent component.
✅ Why we use it:
- To send data from child to parent
- To handle events in the parent based on child interactions
🔧 Example:
// ParentComponent.jsx
import React from "react";
import ChildComponent from "./ChildComponent";
function ParentComponent() {
const handleMessage = (msg) => {
alert("Message from child: " + msg);
};
return <ChildComponent sendMessage={handleMessage} />;
}
export default ParentComponent;
// ChildComponent.jsx
import React from "react";
function ChildComponent({ sendMessage }) {
return (
<button onClick={() => sendMessage("Hello Parent!")}>
Send Message
</button>
);
}
export default ChildComponent;
🔁 Summary:
- Callback functions are passed as props.
- Enable child-to-parent communication.
- Common in form handling, button clicks, and custom hooks.