Function as props
🔹 1. Relationship: Callbacks vs Passing Functions as Props
👉 Key idea:
“Sending data up via callbacks” is a specific use case of passing functions as props.
✅ Passing Functions as Props (General Concept)
React allows you to pass functions just like data:
<Child someFunction={myFunction} />
This is just mechanics:
Parent passes a function
Child can call it
✅ Sending Data Up via Callbacks (Specific Use Case)
This happens when:
The child calls the function
To send data back to the parent
🔁 Example
✅ Parent
function Parent() {
const handleData = (value) => {
console.log("Received from child:", value);
};
return <Child onSend={handleData} />;
}
✅ Child
function Child({ onSend }) {
return (
<button onClick={() => onSend("Hello Parent!")}>
Send Data Up
</button>
);
}
✅ Flow:
Parent → passes function → Child
Child → calls function → Parent receives data
🔹 2. Why is it called “Callback”?
Because:
👉 The parent gives a function to the child
👉 The child calls it back later
Hence:
“callback function”
🔹 3. Is this the ONLY use of passing functions as props?
👉 ❌ NO — this is just one use case
There are multiple important uses:
✅ Use Case 1: Sending Data Up (Most Common)
✔ Child → Parent communication
onChange={(value) => setValue(value)}
✅ Use Case 2: Event Handling
Passing handlers down for UI actions:
function Parent() {
const handleClick = () => alert("Clicked!");
return <Child onClick={handleClick} />;
}
function Child({ onClick }) {
return <button onClick={onClick}>Click</button>;
}
👉 Child doesn’t send data—it just executes behavior
✅ Use Case 3: Reusing Logic
Parent defines logic, children reuse it:
function Parent() {
const calculate = (num) => num * 2;
return <Child compute={calculate} />;
}
function Child({ compute }) {
return <p>{compute(5)}</p>;
}
✅ Use Case 4: Customizing Child Behavior
Parent controls how child behaves:
function Parent() {
const formatText = (text) => text.toUpperCase();
return <Child formatter={formatText} />;
}
🔹 4. Mental Model
Props can carry:
✅ Data
✅ Functions
Direction of Flow:
| Type | Direction |
|---|---|
| Data (props) | Parent → Child |
| Function (callback) | Parent → Child |
| Data via callback | Child → Parent |
🔹 5. Why This Pattern Exists
React enforces:
👉 One-way data flow (Top → Down)
But apps need: 👉 Child → Parent communication
So React enables this pattern:
Parent gives function ↓
Child calls it ↑
🔹 6. Common Confusion (Important)
Many people think:
❌ “Functions are only passed to send data up”
👉 Not true.
✅ Functions are passed for:
handling events
sharing logic
controlling behavior
AND sending data up
🔹 7. One-Line Summary
Passing functions as props is a general capability; sending data up via callbacks is just one specific use case of it.
✅ Final Quick Analogy
Think of it like:
Parent gives child a phone number (function)
Child uses it to call back (callback) and pass info
📞