Closure-lar
Funksiya yarandığı scope-un dəyişənlərinə çıxışı necə saxlayır: sayğac və callback-lərdən tutmuş scope zəncirinə, yaddaşın saxlanmasına və React-dəki stale closure-lara qədər.
Oxu səviyyəsi
Seçilmiş səviyyəyə qədər olan bölmələr göstərilir.
Başlamazdan əvvəl
İlkin şərt yoxdur.
Bu mövzu Junior səviyyəsindən başlayır.
Closure nədir
funksiya ilə onun yarandığı scope-dakı dəyişənlərə çıxışın birləşməsidir. JavaScript-də hər funksiya closure-dur: funksiya yaradılan anda ətrafındakı yadda saxlayır və xarici funksiya işini bitirdikdən sonra da bu çıxışı itirmir.
function makeGreeting(greeting) {
return function (name) {
return greeting + ", " + name + "!";
};
}
const hello = makeGreeting("Hello");
const salam = makeGreeting("Salam");
console.log(hello("Ada")); // "Hello, Ada!"
console.log(salam("Ada")); // "Salam, Ada!"hello("Ada") çağırılanda makeGreeting artıq işini bitirib, amma daxili funksiya greeting-i yenə də oxuyur. makeGreeting-in hər çağırışı öz greeting dəyişənini yaradır, ona görə də hello və salam bir-birinə qarışmır.
Leksik scope
JavaScript qaydası ilə işləyir: funksiyanın hansı dəyişənləri görəcəyi onun harada çağırılmasından yox, kodda harada yazılmasından asılıdır.
const message = "global";
function printMessage() {
console.log(message);
}
function run() {
const message = "local";
printMessage();
}
run(); // "global"printMessage faylın üst səviyyəsində yazılıb, ona görə də message-i elə orada axtarır. run onu çağırsa da, run-ın içindəki message printMessage üçün görünmür.
Əsas məqamlar
- Closure xüsusi sintaksis deyil. Funksiya xarici scope-dakı dəyişəndən istifadə edəndə o, öz-özünə yaranır.
- Daxili funksiya xarici dəyişənləri həm oxuya, həm də dəyişə bilir.
- Daxili scope xarici scope-u görür, xarici scope isə daxildəkiləri görmür.
A is a function together with access to the variables of the scope it was created in. In JavaScript every function is a closure: when a function is created, it remembers the around it, and it keeps that access even after the outer function has returned.
function makeGreeting(greeting) {
return function (name) {
return greeting + ", " + name + "!";
};
}
const hello = makeGreeting("Hello");
const salam = makeGreeting("Salam");
console.log(hello("Ada")); // "Hello, Ada!"
console.log(salam("Ada")); // "Salam, Ada!"makeGreeting has already finished when hello("Ada") runs, yet the inner function still reads greeting. Each call to makeGreeting created its own greeting, so hello and salam don't interfere with each other.
Lexical scope
JavaScript uses : what a function can see is decided by where it is written in the code, not by where it is called from.
const message = "global";
function printMessage() {
console.log(message);
}
function run() {
const message = "local";
printMessage();
}
run(); // "global"printMessage was written at the top level, so it looks up message there. The message inside run is invisible to it, even though run is the caller.
Key points
- A closure is not special syntax. It is simply what happens when a function uses a variable from an outer scope.
- An inner function can read and change outer variables.
- Inner scopes see outer ones; outer scopes cannot see into inner ones.
Gündəlik kodda closure-lar
Closure-lardan hər gün, çox vaxt fərqinə varmadan istifadə edirsən. Ən çox rast gəlinən hallar bunlardır.
Gizli (private) state. Fabrik funksiya elə funksiyalar qaytarır ki, onlar kənardan heç kimin çata bilmədiyi ortaq dəyişəni bölüşür.
function createCounter() {
let count = 0;
return {
increment() {
count += 1;
return count;
},
getValue() {
return count;
},
};
}
const counter = createCounter();
counter.increment();
counter.increment();
console.log(counter.getValue()); // 2
console.log(counter.count); // undefinedcount obyektin xassəsi deyil, createCounter-in scope-unda yaşayır. Onu yalnız increment vasitəsilə dəyişmək olar. createCounter()-i bir də çağırsan, tamamilə müstəqil yeni sayğac alacaqsan.
Hadisə handler-ləri. Handler qurulduğu andakı məlumatı yadda saxlayır:
function setupLikeButton(button, postId) {
let likes = 0;
button.addEventListener("click", () => {
likes += 1;
button.textContent = "Likes: " + likes;
console.log("Liked post " + postId);
});
}Bu yolla qurulan hər düymənin öz likes və öz postId dəyişəni olur.
Callback-lər. filter, map, setTimeout və ya then-ə ötürülən funksiyalar ətrafdakı kodun dəyişənlərini oxuyur:
function filterByMinPrice(products, minPrice) {
return products.filter((product) => product.price >= minPrice);
}Buradakı arrow funksiya həm , həm də minPrice üzərində qurulmuş closure-dur.
React komponentləri. Komponentdəki hər inline handler onu yaradan render-in props və state-i üzərində closure-dur:
import { useState } from "react";
function LikeButton() {
const [likes, setLikes] = useState(0);
return <button onClick={() => setLikes(likes + 1)}>Likes: {likes}</button>;
}Bu kod ona görə işləyir ki, hər render cari likes-ı görən yeni handler yaradır. Köhnə handler öz render-indən uzun yaşayanda nə baş verdiyini mövzunun Senior hissəsində görəcəksən.
You use closures every day, often without noticing. The most common cases:
Private state. A factory function returns functions that share a variable nobody else can reach.
function createCounter() {
let count = 0;
return {
increment() {
count += 1;
return count;
},
getValue() {
return count;
},
};
}
const counter = createCounter();
counter.increment();
counter.increment();
console.log(counter.getValue()); // 2
console.log(counter.count); // undefinedcount is not a property of the object — it lives in the scope of createCounter. The only way to change it is through increment. Call createCounter() again and you get a completely independent counter.
Event handlers. A handler remembers the data it was set up with:
function setupLikeButton(button, postId) {
let likes = 0;
button.addEventListener("click", () => {
likes += 1;
button.textContent = "Likes: " + likes;
console.log("Liked post " + postId);
});
}Every button set up this way gets its own likes and its own postId.
Callbacks. Functions passed to filter, map, setTimeout or then read variables from the surrounding code:
function filterByMinPrice(products, minPrice) {
return products.filter((product) => product.price >= minPrice);
}The arrow function is a and, at the same time, a closure over minPrice.
React components. Every inline handler in a component is a closure over the props and state of the render that created it:
import { useState } from "react";
function LikeButton() {
const [likes, setLikes] = useState(0);
return <button onClick={() => setLikes(likes + 1)}>Likes: {likes}</button>;
}This works because each render creates a new handler that sees the current likes. The senior part of this topic shows what happens when an old handler survives longer than its render.
Closure-lar necə işləyir: mühitlər və scope zənciri
ECMAScript spesifikasiyası closure-ları Environment Record anlayışı ilə təsvir edir; məqalələrdə və spesifikasiyanın köhnə nəşrlərində bu struktur adlanır. Hər mühit bir scope-un binding-lərini (dəyişənlərini) və xarici mühitə istinadı saxlayır.
Demək olar ki, hər şeyi üç qayda izah edir:
- Hər çağırış yeni mühit yaradır. Funksiya çağırılanda onun parametrləri və lokal dəyişənləri üçün təzə mühit yaranır. İçində
let,constvə yaclasselanı olan blokların da öz mühiti olur. - Funksiya harada yarandığını yadda saxlayır. Funksiya obyekti yaradılanda mühərrik cari mühiti həmin obyektin gizli daxili sahəsinə yazır (spesifikasiyada bu sahə Environment adlanır). Funksiya sonradan çağırılanda yeni mühitin xarici istinadı çağıranın mühitinə yox, məhz bu saxlanmış mühitə yönəlir.
- Axtarış zəncir boyunca gedir. Adı tapmaq üçün mühərrik əvvəlcə cari mühitə, sonra onun xarici mühitinə baxır və beləcə qlobal mühitə qədər qalxır. Heç yerdə elan olunmamış adı oxumaq
ReferenceErroratır.
Mühitlərin bu zənciri scope zənciridir (scope chain). Closure isə sadəcə saxladığı mühit sayəsində bu zənciri xarici funksiya qayıtdıqdan sonra da yaşadan funksiyadır.
Dəyəri yox, binding-i tutur
Closure dəyişənin o anki dəyərinin surətini yox, dəyişənin özünü tutur. Eyni çağırış zamanı yaranan closure-lar bir mühiti bölüşür:
function makeBox() {
let value = 0;
const get = () => value;
const set = (next) => {
value = next;
};
return { get, set };
}
const a = makeBox();
const b = makeBox();
a.set(5);
console.log(a.get(), b.get()); // 5 0a.get və a.set eyni mühiti bölüşür, b isə ayrı çağırışdan yarandığı üçün öz mühitinə malikdir.
Hoisting və TDZ
Axtarış funksiya yaradılanda yox, icra olunanda baş verir. Buna görə closure aşağıda elan olunan dəyişənə də müraciət edə bilər:
const read = () => late;
const late = "ready";
console.log(read()); // "ready"read()-i const late sətrindən əvvəl çağırsaydıq, ReferenceError alardıq: sayəsində binding artıq mövcuddur, amma hələ qalır.
The ECMAScript spec describes closures with Environment Records; articles and older editions of the spec call this structure a . An environment holds the bindings (variables) of one scope plus a reference to its outer environment.
Three rules explain almost everything:
- Every call creates a new environment. Calling a function creates a fresh environment for its parameters and local variables. Blocks that contain
let,constorclassdeclarations get their own environment too. - A function remembers where it was created. When a function object is created, the engine stores the current environment in a hidden internal slot of that object (the spec names the slot Environment). When the function is called later, the outer reference of its new environment points to that stored environment — not to the caller's.
- Lookup walks the chain. To resolve a name, the engine checks the current environment, then the outer one, and so on up to the global environment. Reading a name that is not declared anywhere throws a
ReferenceError.
This chain of environments is the scope chain. A closure is simply a function whose stored environment keeps the chain alive after the outer function has returned.
Bindings, not values
A closure captures variables, not snapshots of their values. Closures created during the same call share one environment:
function makeBox() {
let value = 0;
const get = () => value;
const set = (next) => {
value = next;
};
return { get, set };
}
const a = makeBox();
const b = makeBox();
a.set(5);
console.log(a.get(), b.get()); // 5 0a.get and a.set share one environment; b has its own because it came from a separate call.
Hoisting and the TDZ
Lookup happens when the function runs, not when it is created, so a closure can refer to a variable declared further down:
const read = () => late;
const late = "ready";
console.log(read()); // "ready"Calling read() before the const late line would throw a ReferenceError: thanks to the binding already exists, but it is still in the .
Tələlər: dövrdə var və ortaq binding-lər
Müsahibələrin klassik sualı:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// 3, 3, 3var funksiya (və ya qlobal) scope-una aiddir, yəni bütün dövr üçün bir i var. Üç callback-in üçü də həmin binding-i tutur. taymer callback-lərini yalnız cari skript bitəndən sonra işə salır — o vaxta dövr artıq tamamlanıb və i 3-ə bərabərdir.
let ilə nəticə 0, 1, 2 olur:
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// 0, 1, 2for dövrünün başlığında let ilə elan olunan dəyişən üçün spesifikasiya hər iterasiyada yeni binding yaradır və artırma icra olunmazdan əvvəl cari dəyəri ona köçürür. Beləliklə, hər callback ayrı i tutur. let və ya const ilə yazılmış for...of və for...in dövrləri də hər iterasiyada təzə binding alır. (Klassik for (const i = 0; i < 3; i++) isə ilk i++-da TypeError atır, çünki const-a yenidən dəyər mənimsətmək olmaz.)
ES2015-dən əvvəl bu problem hər iterasiya üçün yeni scope yaradan ilə həll olunurdu:
for (var i = 0; i < 3; i++) {
(function (j) {
setTimeout(() => console.log(j), 0);
})(i);
}i arqument kimi ötürüləndə onun cari dəyəri yeni j parametrinə köçürülür.
Digər tələlər
- Snapshot gözləmək. Closure dəyişənin dəyərini icra olunduğu anda oxuyur. Closure yaradılandan çağırılana qədər dəyişən dəyişibsə, yeni dəyəri görəcəksən. Dəyəri "dondurmaq" istəyirsənsə, onu arqument kimi ötür və ya yeni scope-dakı
const-a köçür. - Ortaq və ayrı state. Bir çağırışdan qayıdan funksiyalar mühiti bölüşür, müxtəlif çağırışlardan qayıdanlar isə bölüşmür. Bunu qarışdıranda "bu sayğac niyə dəyişdi?" tipli bug-lar yaranır.
- Adi funksiyalar
this-i tutmur. Adifunction-unthis-i onun necə çağırılmasından asılıdır, ona görə dəsetTimeout(function () { ... })içindəthissənin obyektin olmayacaq. Arrow funksiyaların özthis-i yoxdur: onlar xarici scope-unthis-ini, eynilə tutulmuş dəyişən kimi, istifadə edir.
The classic interview bug:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// 3, 3, 3var is function-scoped (or global), so the whole loop has one i. All three callbacks close over that same binding. The runs the timer callbacks only after the current script has finished — by then the loop is over and i is 3.
With let the output is 0, 1, 2:
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// 0, 1, 2For a let declaration in the head of a for loop, the spec creates a new binding for every iteration and copies the current value into it before the increment runs. Each callback captures a different i. for...of and for...in loops with let or const also get a fresh binding per iteration. (A classic for (const i = 0; i < 3; i++) throws a TypeError on the first i++, because a const cannot be reassigned.)
Before ES2015, the fix was an that created a new scope for each iteration:
for (var i = 0; i < 3; i++) {
(function (j) {
setTimeout(() => console.log(j), 0);
})(i);
}Passing i as an argument copies its current value into a new parameter j.
Other traps
- Expecting a snapshot. A closure reads a variable's value at the moment it runs. If the variable changes between creating the closure and calling it, you get the new value. To freeze a value, pass it as an argument or copy it into a
constin a new scope. - Shared vs. separate state. Functions returned from one call share their environment; functions from different calls do not. Mixing these up leads to "why did this counter change?" bugs.
- Regular functions don't capture
this. A regularfunctiongets itsthisfrom how it is called, so insidesetTimeout(function () { ... })thethisis not your object. Arrow functions have nothisof their own and use thethisof the enclosing scope, just like a closed-over variable.
Faydalı şablonlar: once, memoize, debounce, modul
Bir çox kiçik utilit closure üzərində qurulub. Onların əksəriyyəti : funksiya qəbul edir və gizli state-i closure-da saxlayan yeni funksiya qaytarır.
once — funksiyanı ən çoxu bir dəfə icra etmək:
function once(fn) {
let called = false;
let result;
return function (...args) {
if (!called) {
called = true;
result = fn.apply(this, args);
}
return result;
};
}Qaytarılan funksiya adi function-dur, buna görə this və arqumentlər olduğu kimi ötürülür.
memoize — keşi closure-da yaşayan :
function memoize(fn) {
const cache = new Map();
return (arg) => {
if (!cache.has(arg)) {
cache.set(arg, fn(arg));
}
return cache.get(arg);
};
}Diqqət et: bu keş heç vaxt kiçilmir. Senior hissədə yaddaşdan danışanda buna qayıdacağıq.
debounce — gözləyən taymerin id-sini çağırışlar arasında saxlayır ki, hər yeni çağırış əvvəlkini ləğv edə bilsin:
function debounce(fn, delay) {
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn(...args), delay);
};
}da eyni prinsiplə işləyir, sadəcə taymer id-si əvəzinə son icranın vaxtını (və ya "gözləmə" bayrağını) saxlayır.
Modul şablonu — ES modullarından əvvəl implementasiya detallarını gizlətməyin standart yolu IIFE idi:
const counterModule = (function () {
let count = 0;
return {
increment() {
count += 1;
return count;
},
reset() {
count = 0;
},
};
})();count-a kənardan çatmaq mümkün deyil, ona yalnız increment və reset toxuna bilər. Bu gün hər ES modul faylının öz scope-u olduğundan IIFE-yə nadir hallarda ehtiyac yaranır. Amma ideya — funksiyaları kənara açmaq, state-i closure-da gizlətmək — fabrik funksiyalarda və bir çox kitabxananın API-sində hələ də istifadə olunur.
Many small utilities are built on closures. Most of them are : they take a function and return a new one that keeps private state in a closure.
once — run a function at most one time:
function once(fn) {
let called = false;
let result;
return function (...args) {
if (!called) {
called = true;
result = fn.apply(this, args);
}
return result;
};
}The returned function is a regular function, so this and the arguments are forwarded unchanged.
memoize — with a cache that lives in the closure:
function memoize(fn) {
const cache = new Map();
return (arg) => {
if (!cache.has(arg)) {
cache.set(arg, fn(arg));
}
return cache.get(arg);
};
}Note that this cache never shrinks — the senior section on memory comes back to it.
debounce — a helper keeps the pending timer id between calls, so each new call can cancel the previous one:
function debounce(fn, delay) {
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn(...args), delay);
};
}works the same way, but stores the time of the last run (or a "cooling down" flag) instead of a timer id.
Module pattern — before ES modules, an IIFE was the standard way to hide implementation details:
const counterModule = (function () {
let count = 0;
return {
increment() {
count += 1;
return count;
},
reset() {
count = 0;
},
};
})();count cannot be reached from outside; only increment and reset can touch it. Today every ES module file has its own scope, so the IIFE is rarely needed, but the idea — expose functions, keep state in a closure — is still how factory functions and many library APIs are built.
Yaddaş, garbage collection və performans
Closure öz mühitini əlçatan saxlayır, isə yalnız əlçatmaz olanı təmizləyir. Deməli, dəyişən ona çata bilən hansısa funksiya yaşadıqca yaşayır — o funksiyanın bir daha çağırılıb-çağırılmayacağından asılı olmayaraq.
Sızmaların tipik mənbələri
Closure ilə bağlı çoxu closure-u uzunömürlü bir şeyin saxlamasından yaranır:
- Event listener-lər.
window,documentvə ya qlobal store-a bağlanmış listener silinənə qədər öz closure-unu və onun istinad etdiyi hər şeyi yaşadır. - Taymerlər.
setIntervalcallback-i tutduğu hər şeylə birlikdəclearIntervalçağırılana qədər yaddaşda qalır. - Closure-dakı keşlər. Yuxarıdakı
memoizeheç nəyi unutmur. Ölçü limiti qoy və ya obyekt açarları üçünWeakMapişlət ki, yazılar açarla birlikdə təmizlənə bilsin. - DOM-dan ayrılmış node-lar. Silinmiş elementə istinad edən closure onu bütün alt ağacı ilə birlikdə yaddaşda saxlayır.
Listener-in ömrünü onu yaradan funksionallığa bağla. AbortController öz siqnalı ilə qeydə alınmış bütün listener-ləri bir çağırışla silir:
function trackClicks(button) {
const clicks = [];
const controller = new AbortController();
button.addEventListener("click", (event) => clicks.push(event.timeStamp), {
signal: controller.signal,
});
return () => controller.abort();
}Əslində nə saxlanılır
Spesifikasiya modelində closure bütün mühit zəncirini saxlayır. Mühərriklər bunu optimallaşdırır və adətən yalnız daxili funksiyaların həqiqətən istinad etdiyi dəyişənləri saxlayır, lakin bu optimallaşdırmanın da hüdudları var. V8-də (Chrome, Node.js) scope-dakı hər hansı daxili funksiyanın tutduğu dəyişənlər adətən həmin scope üçün bir ortaq kontekst obyektində saxlanılır və o scope-da yaranan bütün closure-lar bu obyektə istinad edir:
function setup() {
const bigData = new Array(1_000_000).fill(0);
const id = 42;
function logSize() {
console.log(bigData.length);
}
logSize();
return () => id;
}
const getId = setup();getId yalnız id-dən istifadə edir, amma logSize bigData-nı tutduğu üçün hər ikisi eyni kontekstdədir və bigData getId yaşadıqca yaddaşda qala bilər. Bu, spesifikasiyanın yox, mühərrikin detalıdır və versiyadan versiyaya dəyişə bilər. Böyük obyekt qısa müddətə lazımdırsa, onu uzunömürlü scope-da tutma və ya let ilə elan edib işin bitəndə null mənimsət.
Sızmanı tapmaq üçün Chrome DevTools-un Memory panelində heap snapshot götür və yaddaşdan getməli olan obyektin Retainers siyahısına bax.
Performans
Closure yaratmaq funksiya obyekti (dəyişən tutursa, həm də kontekst) üçün yaddaş ayırmaq deməkdir. Bu ucuzdur və çox "isti" kod hissələrindən kənarda nadir hallarda hiss olunur. React-də isə real xərc adətən funksiyanın hər render-də aldığı yeni referansdır: bu, memo-nu faydasız edə və ya effektləri yenidən işə sala bilər.
A closure keeps its environment reachable, and only frees what is unreachable. So a variable lives as long as some function that can still access it is alive — whether or not that function will ever run again.
Typical leak sources
Most closure-related come from a closure held by something long-lived:
- Event listeners. A listener on
window,documentor a global store keeps its closure, and everything it references, alive until removed. - Timers. A
setIntervalcallback and everything it captures stay alive untilclearInterval. - Caches in closures. The
memoizeabove never forgets. Add a size limit, or use aWeakMapfor object keys so entries can be collected with their keys. - Detached DOM nodes. A closure that references a removed element keeps it and its subtree in memory.
Tie a listener's lifetime to the feature that created it. An AbortController removes every listener registered with its signal in one call:
function trackClicks(button) {
const clicks = [];
const controller = new AbortController();
button.addEventListener("click", (event) => clicks.push(event.timeStamp), {
signal: controller.signal,
});
return () => controller.abort();
}What exactly is retained
In the spec model, a closure keeps its whole environment chain. Engines optimize this and typically keep only the variables that inner functions actually reference — but with limits. In V8 (Chrome, Node.js), the variables captured by any inner function are typically stored in one shared context object per scope, and every closure created in that scope points to it:
function setup() {
const bigData = new Array(1_000_000).fill(0);
const id = 42;
function logSize() {
console.log(bigData.length);
}
logSize();
return () => id;
}
const getId = setup();getId only uses id, but logSize captured bigData, so both live in the same context and bigData can stay in memory as long as getId does. This is an engine detail, not spec behavior, and it can change between versions. If a large object is needed only briefly, don't capture it in a long-lived scope, or declare it with let and set it to null when you are done.
To find a leak, take heap snapshots in the Memory panel of Chrome DevTools and inspect the Retainers of the object that should be gone.
Performance
Creating a closure allocates a function object (plus a context if it captures variables) — cheap, and rarely relevant outside very hot code. In React the real cost is usually the new identity a function gets on each render, which can defeat memo or re-trigger effects.
React hook-ları və stale closure
Komponentin hər render-i bir funksiya çağırışıdır. Bu çağırış yeni props, yeni state sabitləri və yeni funksiyalar yaradır; həmin render zamanı yaranan hər effekt, handler və callback məhz o render-in dəyərləri üzərində closure olur. react.dev state-i məhz buna görə "snapshot" adlandırır. Problem köhnə render-dən qalan funksiya işləməyə davam edəndə başlayır — buna deyilir.
import { useEffect, useState } from "react";
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(count + 1);
}, 1000);
return () => clearInterval(id);
}, []);
return <p>{count}</p>;
}Effekt bir dəfə icra olunur, ona görə də interval callback-i count-un 0 olduğu ilk render-ə aiddir. Hər tikdə setCount(0 + 1) çağırılır: sayğac 1 göstərir və orada ilişib qalır.
Həll yolları: sadədən mürəkkəbə
- Funksional yeniləmə. Sənə yalnız əvvəlki state lazımdırsa, onu closure-dan oxuma:
setCount((c) => c + 1). Ən son dəyəri React özü ötürür, effekt[]ilə qalır və interval bir dəfə yaradılır. - Düzgün asılılıqlar.
count-u dependency array-ə əlavə etsən, effekt təzə closure ilə yenidən icra olunacaq. Bu düzgündür, amma bu nümunədə interval hər dəyişiklikdə silinib yenidən yaradılır.react-hooks/exhaustive-depsxəbərdarlığını susdurma: çatışmayan asılılıq adətən gec-tez üzə çıxacaq stale closure deməkdir. Eyni qaydauseCallbackvəuseMemo-ya da aiddir —useCallback(fn, [])ilk render-in dəyərlərini "dondurur". - Ref-lər. Ref bütün render-lərin bölüşdüyü dəyişkən qutudur, ona görə də
ref.current-i oxuyan uzunömürlü callback həmişə son dəyəri alır. Ref-i render zamanı yox, effektdə və ya event handler-də yenilə. useEffectEvent(React 19.2-dən stabildir) — effektin içində son props və ya state-i görməli olan, amma effektin yenidən sinxronlaşmasına səbəb olmamalı olan məntiq üçün:
import { useEffect, useEffectEvent, useState } from "react";
function Ticker({ step }: { step: number }) {
const [count, setCount] = useState(0);
const onTick = useEffectEvent(() => {
setCount((c) => c + step);
});
useEffect(() => {
const id = setInterval(() => onTick(), 1000);
return () => clearInterval(id);
}, []);
return <p>{count}</p>;
}onTick həmişə cari step-i görür, step-in dəyişməsi isə intervalı yenidən başlatmır. Effect Event-lər dependency array-ə yazılmır, yalnız effektlərin içindən çağırılır və başqa komponentlərə və ya hook-lara ötürülmür. Effekti həqiqətən yenidən işə salmalı olan asılılıqları gizlətmək üçün onlardan istifadə etmə.
Every render of a component is a function call. It creates new props, new state constants and new functions, and every effect, handler and callback created during that render closes over that render's values — this is why react.dev describes state as a snapshot. Trouble starts when a function from an old render keeps running: that is a .
import { useEffect, useState } from "react";
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(count + 1);
}, 1000);
return () => clearInterval(id);
}, []);
return <p>{count}</p>;
}The effect runs once, so the interval callback belongs to the first render, where count is 0. Every tick calls setCount(0 + 1): the counter shows 1 and stays there.
Fixes, from simplest
- Functional update. If you only need the previous state, don't read it from the closure:
setCount((c) => c + 1). React passes in the latest value, the effect keeps[], and the interval is created once. - Correct dependencies. Adding
countto the dependency array re-runs the effect with a fresh closure. It is correct, but here it tears down and recreates the interval on every change. Don't silencereact-hooks/exhaustive-deps: a missing dependency is usually a stale closure waiting to happen. The same goes foruseCallbackanduseMemo—useCallback(fn, [])freezes the first render's values. - Refs. A ref is a mutable box shared by all renders, so a long-lived callback that reads
ref.currentalways gets the latest value. Update the ref in an effect or event handler, not during rendering. useEffectEvent(stable since React 19.2) — for logic inside an effect that must see the latest props or state but should not make the effect re-synchronize:
import { useEffect, useEffectEvent, useState } from "react";
function Ticker({ step }: { step: number }) {
const [count, setCount] = useState(0);
const onTick = useEffectEvent(() => {
setCount((c) => c + step);
});
useEffect(() => {
const id = setInterval(() => onTick(), 1000);
return () => clearInterval(id);
}, []);
return <p>{count}</p>;
}onTick always sees the current step, and changing step does not restart the interval. Effect Events are left out of the dependency array, may only be called from inside effects, and must not be passed to other components or hooks. Don't use them to hide dependencies that really should re-run the effect.
Müsahibə üçün məsləhətlər
30 saniyəlik tərif. "Closure funksiya ilə onun yarandığı scope-un dəyişənlərinin birləşməsidir. JavaScript dəyişənləri leksik qaydada həll edir, ona görə də xarici funksiya qayıtdıqdan sonra da funksiya bu dəyişənlərə çıxışını saxlayır." Ardınca sayğac fabrikini yaz: bu, ideyanı sadəcə əzbərləmədiyini, tətbiq edə bildiyini göstərir.
Gözlənilən suallar
- Bu dövr nə çap edəcək?
var/let+setTimeouttapmacası. Səbəbini izah et: bir ortaq binding və hər iterasiya üçün yeni binding. once,memoizevə yadebounceyaz. State-in harada yaşadığını (closure-da) de və detallara diqqət et:this-in və arqumentlərin ötürülməsi, əvvəlki taymerin təmizlənməsi.- Məlumatı necə gizli saxlamaq olar? Closure-larla (fabrik funksiya və ya modul şablonu); siniflər üçün müasir alternativ kimi
#privatesahələrini də qeyd et. - Closure yaddaş sızmasına səbəb ola bilərmi? Bəli, çünki o, öz mühitini əlçatan saxlayır. Konkret mənbələr say: unudulmuş listener-lər, təmizlənməyən intervallar, limitsiz keşlər.
- Effekt niyə köhnə dəyəri görür? Hər render-in öz closure-ları var. Həll yolları: asılılıqlar, funksional yeniləmə, ref-lər,
useEffectEvent.
Bal itirdən səhvlər
- Closure-un dəyişənləri "kopyaladığını" demək. O, binding-ləri tutur, ona görə yaradılandan sonrakı dəyişikliklər də görünür.
- Closure-un yalnız funksiya qaytarılanda yarandığını demək. Hər funksiya öz scope-u üzərində closure-dur; onu qaytarmaq və ya başqa yerə ötürmək sadəcə bu effekti görünən edir.
- Scope ilə
this-i qarışdırmaq. Closure dəyişənləri tutur, adi funksiyadathisisə çağırışdan asılıdır. - Closure-ları təbiətcə yavaş və ya sızma yaradan hesab etmək. Onların xərci bir yaddaş ayrılmasıdır və istinad etdikləri şeyləri yalnız özləri əlçatan qaldıqca saxlayırlar.
Senior səviyyəni göstərən məqamlar
Nəzəriyyəni təcrübə ilə bağla: sızmanı necə tapardın (heap snapshot, Retainers), sabit funksiya referansı memo və effekt asılılıqları üçün niyə vacibdir, funksional yeniləməni, ref-i və ya useEffectEvent-i nə vaxt seçərdin.
A 30-second definition. "A closure is a function plus the variables of the scope where it was created. JavaScript resolves variables lexically, so the function keeps access to them even after the outer function has returned." Then sketch a counter factory: it shows you can apply the idea, not just recite it.
Questions you are likely to get
- What does this loop log? The
var/let+setTimeoutpuzzle. Explain why: one shared binding vs. a new binding per iteration. - Implement
once,memoizeordebounce. Say where the state lives (in the closure) and handle the details: forwardingthisand arguments, clearing the previous timer. - How do you make data private? Closures (factory function or module pattern); for classes, mention
#privatefields as the modern alternative. - Can closures cause memory leaks? Yes — they keep their environment reachable. Name concrete sources: forgotten listeners, intervals that are never cleared, unbounded caches.
- Why does my effect see an old value? Each render has its own closures. Fixes: dependencies, functional updates, refs,
useEffectEvent.
Mistakes that cost points
- Saying closures "copy" variables. They capture bindings, so changes made after creation are visible.
- Saying a closure exists only when a function is returned. Every function closes over its scope; returning it or passing it somewhere just makes the effect visible.
- Mixing up scope and
this. Closures capture variables;thisin a regular function depends on the call. - Calling closures slow or leaky by nature. They cost an allocation and retain what they reference while they are reachable — no more than that.
Senior signal
Connect the theory to practice: how you would find a leak (heap snapshot, Retainers view), why a stable function identity matters for memo and effect dependencies, and when you would choose a functional update, a ref or useEffectEvent.
Closure-ları review edərkən nəyi yoxlamalı
Bu siyahını yazmadığın kodu review edəndə işlət: komanda yoldaşının pull request-i, kitabxananın issue tracker-indəki snippet və ya AI assistentin təklifi. Bu yoxlamaları etməsən, köhnə dəyərləri oxuyan callback-lər, ya da funksionallıq çoxdan yox olsa da yaddaşı tutan listener və keşlər production-a çıxacaq.
- Render-indən uzun yaşayan callback state-i və ya props-u birbaşa oxuyurmu? Interval callback-i,
[]ilə yazılmış effekt və yauseCallback(fn, [])onu yaradan render-in dəyərlərini saxlayır — buna deyilir.setCount((c) => c + 1)kimi funksional yeniləmə, düzgün asılılıqlar və ya ref gözlə;react-hooks/exhaustive-depsxəbərdarlığı isə susdurulmamalıdır. window,documentvə ya qlobal store-a bağlanan hər listener silinirmi, hərsetIntervaltəmizlənirmi? Bu baş verənə qədər nə closure-u, nə də onun istinad etdiyi şeyləri təmizləyə bilir. UyğunremoveEventListener,clearIntervalvə yacontroller.abort()çağırışını tap.- Callback yaradan dövr
varişlədirmi?for (var i = 0; i < 3; i++)ilə üç taymer callback-i biri-ni bölüşür və3, 3, 3çap edir. Dövrün başlığındalet,for...of-da isəconstgözlə. - Kod closure-un yarandığı andakı dəyəri gözləyirmi? Closure dəyərin surətini yox, dəyişənin özünü tutur və onu icra olunanda oxuyur. Dəyəri "dondurmaq" üçün onu arqument kimi ötür və ya
const-a köçür. - Adi
functioncallback-ithisişlədirmi?setTimeout(function () { ... })içindəthissənin obyektin olmayacaq: closure dəyişənləri tutur,this-i yox. Arrow funksiya,oncekimi wrapper-lərdə isəfn.apply(this, args)gözlə. - Closure-dakı keş yalnız böyüyürmü?
Mapüzərində qurulmuşmemoizeheç nəyi unutmur. Ölçü limiti qoyulmasını, açarlar obyektdirsə,WeakMapişlədilməsini tələb et.
Use this list when you review code you did not write: a teammate's pull request, a snippet from a library's issue tracker or a suggestion from an AI assistant. Skip it and you ship callbacks that read old values, or listeners and caches that hold memory long after the feature is gone.
- Does a callback that outlives its render read state or props directly? An interval callback, an effect with
[]oruseCallback(fn, [])keeps the values of the render that created it: a . Expect a functional update likesetCount((c) => c + 1), correct dependencies or a ref, not a silencedreact-hooks/exhaustive-deps. - Is every listener on
window,documentor a global store removed, and everysetIntervalcleared? Until then, cannot free the closure or anything it references. Find the matchingremoveEventListener,clearIntervalorcontroller.abort(). - Does a loop that creates callbacks use
var? Withfor (var i = 0; i < 3; i++), three timer callbacks share oneiand log3, 3, 3. Expectletin the loop head, orconstinfor...of. - Does the code expect the value from the moment the closure was created? A closure captures the variable, not a snapshot, and reads it when it runs. To freeze a value, pass it as an argument or copy it into a
const. - Does a regular
functioncallback usethis? InsidesetTimeout(function () { ... }),thisis not your object: closures capture variables, notthis. Expect an arrow function, orfn.apply(this, args)in wrappers such asonce. - Does a cache inside a closure only grow? A
memoizebuilt on aMapnever forgets. Ask for a size limit, or aWeakMapwhen the keys are objects.
Özünü yoxla
Təcrübədə sına
Bu mövzudan istifadə edən praktiki işlər.
İnsident simulyatoru
Sistem dizaynı
Həftəlik çağırışlar
Frontend tarixi
Real kodda gör
Buna əsaslanan real kitabxanaların mənbə kodu üzrə bələdçili turlar.