top of page
Logo der Online Agentur mdwp

Callback Function

A Callback Function in React JS is a function that gets passed as an argument into another function, to be executed later. It's a form of "continue the conversation later" approach in JavaScript, and it's prominent in React because React is built on JavaScript. Callback functions allow for asynchronous behavior, meaning they are great for operations that take time and should not halt the flow of the program while processing, like loading data from an API or database.

In simple terms, when function A is run, it will run function B (the callback function) at some point during its execution.

Here's a simple code snippet to illustrate:

```jsx
// Callback function definition
function myCallbackFunction() {
console.log('Hello, I am a callback function!');
}

// Function that receives another function (a callback) as argument
function myMainFunction(callback) {
console.log('Hello, I am the main function');
callback();
}

// Using the function
myMainFunction(myCallbackFunction);

// Output:
// Hello, I am the main function
// Hello, I am a callback function!
```

In this script, `myMainFunction` is called with `myCallbackFunction` as an argument. Inside `myMainFunction`, the callback is invoked. In a real-world React component, a callback might be something like an event handler function that's passed as a prop to a child component:

```jsx
// Parent component
class Parent extends React.Component {
handleClick() {
console.log('Button clicked in Child component');
}

render() {
return (
<Child onClick={this.handleClick} />
)
}
}

// Child component
class Child extends React.Component {
render() {
return (
<button onClick={this.props.onClick}>Click Me!</button>
)
}
}
```
In the above example, when the button in `Child` component is clicked, it triggers the `handleClick` function in the `Parent` component.

bottom of page