يبني نموذج الحالة الذري (Jotai, Recoil) الحالة العامة من وحدات صغيرة وعديدة ومستقلة تُسمى atoms، مركّبة من الأسفل إلى الأعلى — بدلاً من متجر واحد كبير من الأعلى إلى الأسفل (Redux) أو context أحادي. تشترك المكونات في atoms فردية وتُعاد تصييرها فقط عندما تتغير تلك الذرات.
أصغر وحدات الحالة — الذرات
import { atom, useAtom } from "jotai";
const countAtom = atom(0); // a primitive atom — one piece of state
const nameAtom = atom("Ann"); // another, independent
كل atom هي قطعة حالة مستقلة بذاتها. تنشئ عدد من الذرات حسب احتياجك، كل واحدة قابلة للتخاطب بشكل مستقل.
الذرات المشتقة — التركيب
// a derived atom computes from other atoms; recomputes when its dependencies change
const doubleAtom = atom((get) => get(countAtom) * 2);
const greetingAtom = atom((get) => `Hello, ${get(nameAtom)}`);
// writable derived atom
const upperNameAtom = atom(
(get) => get(nameAtom).toUpperCase(),
(get, set, newVal) => set(nameAtom, newVal.toLowerCase()),
);
تتركب الذرات في رسم بياني للتبعيات — الذرات المشتقة تُحدّث نفسها تلقائياً عندما تتغير الذرات التي تقرأها، مثل جدول بيانات.
استخدام الذرات — يشعر وكأنه useState، لكنه عام
function Counter() {
const [count, setCount] = useAtom(countAtom); // global, but useState-like API
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
function Display() {
const [double] = useAtom(doubleAtom); // re-renders ONLY when doubleAtom changes
}
ذري (من الأسفل إلى الأعلى) مقابل متجر (من الأعلى إلى الأسفل)
Redux (top-down): one big state tree; you carve slices/selectors OUT of it
Atomic (bottom-up): start with tiny atoms; compose them UP into derived state
Granularity: each atom is independently subscribable → naturally fine-grained
re-renders (a component using countAtom ignores nameAtom changes)
الفوائد والمقابلات
✓ Fine-grained re-renders by default (subscribe to exactly the atoms you use)
✓ No selector boilerplate; derived state is just another atom
✓ Solves Context's "re-render everything" problem
✓ Great for state that's naturally decomposed into many independent pieces
✗ Many atoms can be harder to organize/trace than one centralized store
✗ Less rigid structure than Redux (a pro or con depending on the team)
لماذا يهم
النموذج الذري هو نهج متميز وشائع بشكل متزايد للحالة العامة يقلب بنية Redux من الأعلى إلى الأسفل: بدلاً من تقسيم متجر كبير، تركب ذرات صغيرة من الأسفل إلى الأعلى.
تمنح درجة التفصيل المدمجة فيها إعادة تصيير فعالة وموجهة دون الحاجة إلى محددات — معالجة مشاكل الأداء في Context مباشرة.
فهم الذرات (والذرات المشتقة) يكمل معرفتك بمساحة تصميم إدارة الحالة، جنباً إلى جنب مع نماذج المتجر الفردي (Redux/Zustand) والتفاعلية (MobX/Signals)، مما يساعدك على اختيار النموذج الذي يناسب شكل حالة التطبيق بشكل أفضل.
