Learn the concept
Closures
A closure is a function that has access to variables from its outer (enclosing) scope, even after the outer function has returned. They're useful for data privacy, state management, and creating function factories.
A closure is created when a function is defined inside another function, and the inner function references variables from the outer function's scope.
How Closures Work:
Common Use Cases:
function createCounter() {
let count = 0; // Private variable
return function() {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
// count is not accessible directly
console.log(count); // ReferenceErrorCreating private variables and methods inaccessible from outside, enabling encapsulation without classes
useState and useEffect internally rely on closures to preserve state between renders and associate state with component instances
Caching expensive computation results using closure-held cache objects to avoid redundant calculations
Build a module with private state exposed through public increment, decrement, and getCount methods using closures
Implement a generic memoize function using closures to cache function results based on arguments
Hooks like useState and useEffect use closures to associate state with component instances across re-renders