Closure

الإغلاق (Closure)

Intermediateprogramming1 min read
js closurelexical scopeencapsulationcaptured variable

Definition

A function that remembers and has access to variables from its outer scope, even after that scope has closed.

دالة تتذكر وتصل إلى المتغيرات من نطاقها الخارجي، حتى بعد إغلاق ذلك النطاق.

Why It Matters

The stale closure bug is one of the most common React mistakes — useEffect running with an outdated value because it captured an old copy via closure.

خطأ الإغلاق القديم هو أحد أكثر أخطاء React شيوعًا — useEffect يعمل بقيمة قديمة لأنه التقط نسخة قديمة عبر الإغلاق.

Full Definition

A closure is created when a function 'closes over' variables from its enclosing scope — it retains access to those variables even after the outer function has returned. React hooks heavily use closures: useState setters capture the current state value. Event handlers inside React components close over props and state. Understanding closures prevents subtle bugs with stale values in useEffect.
يُنشأ الإغلاق عندما 'تغلق' الدالة على متغيرات من نطاقها المحيط — تحتفظ بالوصول إليها حتى بعد إعادة الدالة الخارجية. تستخدم خطافات React الإغلاقات بشكل مكثف: setters الـuseState تلتقط قيمة الحالة الحالية.

Example Usage

function makeCounter() { let count = 0; return () => ++count; } const counter = makeCounter(); counter(); // 1, counter(); // 2

function makeCounter() { let count = 0; return () => ++count; } const counter = makeCounter(); counter(); // 1، counter(); // 2

Knowledge Graph

Avoid these mistakes when using Closure:

1

Stale closures in useEffect — forgetting to add dependencies to the dependency array

2

Capturing loop variables in closures — use let not var

Sign in to unlock guided AI explanations from AI Teacher.

Generate a Prompt

Copy this prompt and use it directly with any AI model — no setup needed.

Ready-to-Use Prompt
Help me build a project using Closure.

Explain:
1. What is Closure and why it matters
2. The core architecture and required tools
3. Step-by-step implementation plan
4. Common mistakes to avoid: Stale closures in useEffect — forgetting to add dependencies to the dependency array, Capturing loop variables in closures — use let not var
5. Best practices and production tips

Official Resources