Skip to content
doubtly

2 answers

A callback function is a function passed as an argument to another function, to be called later when some task is finished or an event happens.

function loadData(done) {
  setTimeout(() => done("data ready"), 1000);
}
loadData(function (msg) { console.log(msg); });  // callback

Purpose:

  • To handle asynchronous work (timers, API calls, file reading) without blocking the program.
  • To respond to events, e.g. onClick={handleClick} in React.
  • To let a child component send data to its parent: the parent passes a function as a prop and the child calls it.
  • In React class components, setState is asynchronous, so it accepts a callback as a second argument that runs after the state has updated and the component has re-rendered:
    this.setState({ count: 1 }, () => console.log(this.state.count));
Doubtly AI · 24 Oct 2026 AI-verified · Oct 2026 Report
Was this answer helpful?

Your answer

Log in or create a free account to answer this question.