useRef

useRef

Intermediatereact1 min read
use refrefdom refreact refmutable ref

Definition

A React hook that returns a mutable ref object — used for accessing DOM elements or persisting values without causing re-renders.

خطاف React يُعيد كائن ref قابل للتغيير — يُستخدم للوصول إلى عناصر DOM أو الاحتفاظ بالقيم دون التسبب في إعادة التصيير.

Why It Matters

The PromptModal accessibility focus trap uses useRef to access the dialog DOM node and query all focusable elements inside it. Without useRef, there's no way to find DOM children from a React component.

فخ التركيز لإمكانية الوصول في PromptModal يستخدم useRef للوصول إلى عقدة DOM للحوار والاستعلام عن جميع العناصر القابلة للتركيز داخلها.

Full Definition

useRef returns an object with a `.current` property. When used as a `ref` prop on JSX elements, `.current` points to the DOM node. Changing `.current` does NOT cause re-renders. Common uses: (1) DOM access for focus management, scroll position, animations; (2) storing previous values; (3) mutable values that shouldn't trigger renders (like timer IDs). The PromptModal focus trap in 404Fault uses `const dialogRef = useRef<HTMLDivElement>(null)` to query focusable elements.
useRef يُعيد كائنًا بخاصية `.current`. عند استخدامه كـprop `ref` على عناصر JSX، تشير `.current` إلى عقدة DOM. تغيير `.current` لا يُسبّب إعادة التصيير. استخدامات شائعة: الوصول إلى DOM لإدارة التركيز، وتخزين القيم السابقة.

Example Usage

const dialogRef = useRef<HTMLDivElement>(null); // later: dialogRef.current?.querySelectorAll('button, [href]')

const dialogRef = useRef<HTMLDivElement>(null); // لاحقًا: dialogRef.current?.querySelectorAll('button, [href]')

Knowledge Graph

Avoid these mistakes when using useRef:

1

Storing state that should cause re-renders in a ref — use useState instead

2

Accessing ref.current before the component mounts — it's null until after the first render

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

Explain:
1. What is useRef and why it matters
2. The core architecture and required tools
3. Step-by-step implementation plan
4. Common mistakes to avoid: Storing state that should cause re-renders in a ref — use useState instead, Accessing ref.current before the component mounts — it's null until after the first render
5. Best practices and production tips

Official Resources