useCallback

useCallback

Intermediatereact1 min read
use callbackmemoized callbackcallback hookmemo callback

Definition

A React hook that memoizes a function so it keeps the same reference between renders unless dependencies change.

خطاف React يحفظ دالة في الذاكرة المؤقتة حتى تحتفظ بنفس المرجع بين عمليات التصيير إلا إذا تغيرت التبعيات.

Why It Matters

Without useCallback, a function like `const handleClose = () => setOpen(false)` gets a new identity on every parent re-render, potentially causing unnecessary child re-renders.

بدون useCallback، دالة مثل `const handleClose = () => setOpen(false)` تحصل على هوية جديدة عند كل إعادة تصيير للوالد، مما قد يسبب إعادة تصيير غير ضرورية للأبناء.

Full Definition

useCallback wraps a function and returns a memoized version that only changes when its dependencies change. This is useful when passing callbacks to child components that are wrapped in React.memo — without useCallback, every parent re-render creates a new function reference, causing the child to re-render too. It's a performance optimization tool, not something needed in every component.
useCallback يلفّ دالة ويُعيد نسخة محفوظة في الذاكرة المؤقتة لا تتغير إلا عند تغيير تبعياتها. مفيد عند تمرير الاستدعاءات إلى مكونات فرعية مُغلَّفة بـReact.memo.

Example Usage

const onClose = useCallback(() => setSelectedPrompt(null), []);

const onClose = useCallback(() => setSelectedPrompt(null), []);

Knowledge Graph

Avoid these mistakes when using useCallback:

1

Adding useCallback everywhere 'for performance' — it adds overhead; only use it for callbacks passed to memoized children

2

Wrong or empty dependency array — can cause stale closure bugs

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 useCallback.

Explain:
1. What is useCallback and why it matters
2. The core architecture and required tools
3. Step-by-step implementation plan
4. Common mistakes to avoid: Adding useCallback everywhere 'for performance' — it adds overhead; only use it for callbacks passed to memoized children, Wrong or empty dependency array — can cause stale closure bugs
5. Best practices and production tips

Official Resources