أتقن React Hooks المتقدمة: useCallback و useMemo و useReducer والـ Hooks المخصصة وأنماط التحسين. الدليل الشامل لمطوري React.
# React Hooks الدليل المتقدم
تعلم إتقان React Hooks المتقدمة لبناء تطبيقات فعالة وقابلة للصيانة.
## الـ Hooks الأساسية مع TypeScript
### useState مع الأنواع
```typescript
import { useState } from "react";
interface User {
id: number;
name: string;
email: string;
isActive: boolean;
}
function UserProfile() {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
const [errors, setErrors] = useState<string[]>([]);
const updateName = (newName: string) => {
setUser((prev) =>
prev ? { ...prev, name: newName } : null
);
};
return (
<div dir="rtl">
{loading ? (
<p>جاري التحميل...</p>
) : user ? (
<h1>مرحباً، {user.name}</h1>
) : (
<p>المستخدم غير موجود</p>
)}
</div>
);
}
```
## useReducer للحالات المعقدة
```typescript
interface Product {
id: string;
name: string;
price: number;
quantity: number;
}
interface CartState {
items: Product[];
total: number;
itemCount: number;
}
type CartAction =
| { type: "ADD_ITEM"; payload: Product }
| { type: "REMOVE_ITEM"; payload: string }
| { type: "CLEAR_CART" };
function cartReducer(state: CartState, action: CartAction): CartState {
switch (action.type) {
case "ADD_ITEM": {
const existing = state.items.find((p) => p.id === action.payload.id);
if (existing) {
const updatedItems = state.items.map((p) =>
p.id === action.payload.id
? { ...p, quantity: p.quantity + 1 }
: p
);
return calculateTotals({ ...state, items: updatedItems });
}
return calculateTotals({
...state,
items: [...state.items, { ...action.payload, quantity: 1 }],
});
}
case "REMOVE_ITEM": {
const filteredItems = state.items.filter((p) => p.id !== action.payload);
return calculateTotals({ ...state, items: filteredItems });
}
case "CLEAR_CART":
return { items: [], total: 0, itemCount: 0 };
default:
return state;
}
}
```
## الـ Hooks المخصصة
### useLocalStorage
```typescript
import { useState, useEffect } from "react";
export function useLocalStorage<T>(
key: string,
initialValue: T
): [T, (value: T | ((prev: T) => T)) => void] {
const [storedValue, setStoredValue] = useState<T>(() => {
if (typeof window === "undefined") return initialValue;
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error("خطأ في قراءة التخزين المحلي:", error);
return initialValue;
}
});
useEffect(() => {
try {
window.localStorage.setItem(key, JSON.stringify(storedValue));
} catch (error) {
console.error("خطأ في الكتابة إلى التخزين المحلي:", error);
}
}, [key, storedValue]);
return [storedValue, setStoredValue];
}
// مثال على الاستخدام
function Settings() {
const [theme, setTheme] = useLocalStorage("theme", "فاتح");
const [language, setLanguage] = useLocalStorage("language", "ar");
return (
<div dir="rtl">
<button onClick={() => setTheme(theme === "فاتح" ? "داكن" : "فاتح")}>
المظهر الحالي: {theme}
</button>
</div>
);
}
```
## تحسين الأداء
```typescript
import { useMemo, useCallback, memo } from "react";
export function ProductList({
products,
selectedCategory,
onSelect,
}: {
products: Product[];
selectedCategory: string;
onSelect: (id: string) => void;
}) {
// تخزين المنتجات المفلترة
const filteredProducts = useMemo(() => {
console.log("جاري تصفية المنتجات...");
return products.filter(
(p) => !selectedCategory || p.category === selectedCategory
);
}, [products, selectedCategory]);
// تخزين دالة النقر
const handleClick = useCallback(
(id: string) => {
onSelect(id);
},
[onSelect]
);
return (
<ul className="grid grid-cols-3 gap-4" dir="rtl">
{filteredProducts.map((product) => (
<ProductCard
key={product.id}
product={product}
onClick={handleClick}
/>
))}
</ul>
);
}
```
هذا الدليل المتقدم لـ React Hooks يساعد المطورين الناطقين بالعربية على إتقان أفضل الممارسات وتقنيات تحسين الأداء.This react prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their react implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For react projects, consider mentioning your framework version, coding style, and any specific libraries you're using.