Sobes.tech
Middle+

Provide an example of a closure. Have you used closures in React?

sobes.tech AI

Answer from AI

A closure is a function that 'remembers' the environment in which it was created, including access to variables from an outer function even after the outer function has finished execution.

Example of a closure in JavaScript:

function makeCounter() {
  let count = 0;
  return function() {
    count += 1;
    return count;
  };
}

const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2

In React, closures are often used, for example, in hooks and event handlers to preserve state or access variables from the external context. For instance, in useEffect or callbacks, where it is important to keep a reference to current data or functions.

Provide an example of a closure. Have you used… - sobes.tech