Custom Hook

الخطاف المخصص (Custom Hook)

Intermediatereact1 min read
custom react hookuseX hookcomposable hookhook abstraction

Definition

A JavaScript function starting with 'use' that encapsulates reusable React hook logic.

دالة JavaScript تبدأ بـ'use' تُغلّف منطق خطاف React قابل لإعادة الاستخدام.

Why It Matters

useAuth() and useLanguage() are the two most-used custom hooks in 404Fault. Understanding how custom hooks work helps you read every component that uses them.

useAuth() وuseLanguage() هما أكثر الخطافات المخصصة استخدامًا في 404Fault. فهم كيفية عمل الخطافات المخصصة يساعدك على قراءة كل مكوّن يستخدمها.

Full Definition

Custom hooks let you extract and reuse stateful logic between components. Any function that calls built-in hooks (useState, useEffect, etc.) and starts with `use` is a custom hook. Examples in 404Fault: `useAuth()` (wraps useContext + AuthContext), `useLanguage()` (wraps useContext + LanguageContext), `useGlossaryIndex()` (fetches terms and builds search index). Custom hooks clean up components by moving logic out.
الخطافات المخصصة تتيح استخراج وإعادة استخدام المنطق المرتبط بالحالة بين المكونات. أي دالة تستدعي خطافات مدمجة وتبدأ بـ`use` هي خطاف مخصص. أمثلة في 404Fault: `useAuth()` و`useLanguage()` و`useGlossaryIndex()`.

Example Usage

// src/hooks/useGlossaryIndex.ts export function useGlossaryIndex() { const [index, setIndex] = useState(null); useEffect(() => { fetchAndBuild().then(setIndex); }, []); return index; }

// src/hooks/useGlossaryIndex.ts export function useGlossaryIndex() { const [index, setIndex] = useState(null); useEffect(() => { fetchAndBuild().then(setIndex); }, []); return index; }

Knowledge Graph

Avoid these mistakes when using Custom Hook:

1

Not starting the hook name with 'use' — React can't enforce the rules of hooks on it

2

Calling a custom hook conditionally — hooks must always be called in the same order

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 Custom Hook.

Explain:
1. What is Custom Hook and why it matters
2. The core architecture and required tools
3. Step-by-step implementation plan
4. Common mistakes to avoid: Not starting the hook name with 'use' — React can't enforce the rules of hooks on it, Calling a custom hook conditionally — hooks must always be called in the same order
5. Best practices and production tips

Official Resources