Callback
IT Industry-Academia Bridge Program
Callback Function
A callback function is a function you give to another function to run
later, when something specific happens or finishes.
It allows child → parent communication. function Parent() {
const sayHello = (name) => {
[Link]("Hello, " + name);
};
• Parent defines sayHello — this is the callback.
return <Child onGreet={sayHello} />;
• Parent passes it as onGreet prop to Child. }
• Child calls onGreet("Alex") when the button is clicked. function Child({ onGreet }) {
return (
• Parent’s sayHello runs with "Alex" as the argument. <button onClick={() => onGreet("Alex")}>
Greet Parent
</button>
);
}
Callback Analogy
Parent component
├─ defines handleSomething() function
└─ passes handleSomething as a prop to Child
Child component
└─ receives handleSomething prop
└─ calls it when an event happens (like a button click)
IT Industry-Academia Bridge Program
Callback Function
Callback functions let children talk to parents
import React, { useState } from "react";
function Child({ count, onIncrement }) {
function Parent() { return (
const [count, setCount] = useState(0); <div>
<p>Child sees count: {count}</p>
const handleIncrement = () => { <button onClick={onIncrement}>Increase Count</button>
setCount(count + 1); // update parent state </div>
}; );
}
return (
<div>
<h1>Parent Count: {count}</h1>
<Child count={count} onIncrement={handleIncrement} />
</div>
);
}
Callback Function
Callback functions is a way ‘two way binding’
function Parent() {
const [text, setText] = [Link]("");
return (<div>
<Child text={text} setText={setText} />
<p>Parent sees: {text}</p> function Child({ text, setText }) {
</div>) return (
} <input
type="text"
value={text} // Child reads value from parent
onChange={(e) => setText([Link])} // Child updates parent
/>
);
}
IT Industry-Academia Bridge Program
IT Industry-Academia Bridge Program