top of page
Logo der Online Agentur mdwp

Closure

In JavaScript, a closure is not a feature specific to React, but rather a core concept of JavaScript itself that's used in React and various other frameworks. Closure is essentially a function bundled together (enclosed) with references to its surrounding state (lexical environment).

In simpler words, it gives you access to an outer function’s scope from an inner function. This means if a function is defined inside another function, the inner function has access to the outer function's variables and parameters, even after the outer function has returned. It 'remembers' the context in which it was created.

Here's an example of a closure:

```jsx
function greeting(name) {
let greetMsg = 'Hello ' + name;
function displayGreeting() {
console.log(greetMsg);
}
displayGreeting();
}
greeting('John'); // Output: Hello John
```

In this example, `displayGreeting` is a closure that is defined inside `greeting` and has access to `greeting`'s environment variables. Here, `greetMsg` is a variable that's part of the closure's state.

React often uses closures in event handlers, where you might want to access a prop or state.

For example:

```jsx
class Example extends React.Component {
handleClick = () => {
console.log('Prop value is: ', this.props.value);
}

render() {
return <button onClick={this.handleClick}>Click Me</button>
}
}
```

In this click handler, `this.props.value` is part of the closure, and it can "remember" its value even if it changes elsewhere. This is possible because the event handler forms a closure around the `render` method's environment, which includes the current `props` and `state`.

bottom of page