حفظ الحالة في localStorage
حافظ على حالة العميل بعد إعادة تحميل الصفحات عبر حفظها في localStorage، ومعالجة hydration بأمان في Next.js، واستخدام middleware باسم persist في Zustand.
حفظ الحالة في localStorage درس مجاني في Next.js 15 Fullstack (App Router + Server Actions) على CoddyKit. هذا هو الدرس 4 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Next.js 15 Fullstack (App Router + Server Actions)، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Next.js 15 Fullstack (App Router + Server Actions) 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Why Persist State?
By default, React state vanishes on reload. Persistence saves data like theme, cart contents, or draft text to the browser so it survives refreshes and revisits.
Meet localStorage
localStorage is a browser key-value store that keeps strings indefinitely. It is synchronous and scoped to the origin.
localStorage.setItem('theme', 'dark');
const theme = localStorage.getItem('theme');Storing Objects
localStorage only holds strings, so serialize objects with JSON.stringify when saving and JSON.parse when reading.
localStorage.setItem('cart', JSON.stringify({ items: 3 }));
const cart = JSON.parse(localStorage.getItem('cart') || '{}');The SSR Problem
Next.js renders components on the server first, where window and localStorage do not exist. Accessing them during render throws an error.
You must read localStorage only after the component mounts in the browser.
Reading Safely in useEffect
Read persisted state inside useEffect, which runs only on the client. Start with a safe default for the server render.
'use client';
const [theme, setTheme] = useState('light');
useEffect(() => {
const saved = localStorage.getItem('theme');
if (saved) setTheme(saved);
}, []);Writing on Change
Sync state back to localStorage whenever it changes with another effect.
useEffect(() => {
localStorage.setItem('theme', theme);
}, [theme]);Avoiding Hydration Mismatch
If the server renders 'light' but the client immediately shows 'dark', React warns about a hydration mismatch. Render persisted UI only after a mounted flag is true.
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
if (!mounted) return null;Persisting Zustand Stores
Zustand ships a persist middleware that automatically saves your whole store to localStorage. Wrap your store creator with it.
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
export const useCart = create(persist(
(set) => ({ items: [], add: (i) => set((s) => ({ items: [...s.items, i] })) }),
{ name: 'cart-storage' }
));Choosing What to Persist
You rarely want to persist everything. Use partialize to save only the fields that matter and keep transient UI state in memory.
persist(storeFn, {
name: 'cart-storage',
partialize: (s) => ({ items: s.items })
});Versioning & Migration
When your state shape changes, bump version and provide a migrate function so old stored data upgrades instead of breaking the app.
persist(storeFn, {
name: 'cart-storage',
version: 2,
migrate: (old, from) => ({ ...old, currency: 'USD' })
});Best Practices
Persist state responsibly:
- Serialize objects with JSON
- Read only on the client to avoid SSR errors
- Guard against hydration mismatches
- Use Zustand persist with partialize and versioning
Quick Check
Test your persistence knowledge.
Recap
You learned to persist client state:
- Store strings in
localStorage, serializing objects with JSON - Read in
useEffectand guard with amountedflag - Use Zustand's
persistmiddleware withpartializeand versioned migrations
Your app now remembers user state across reloads.
الأسئلة الشائعة
هل درس «حفظ الحالة في localStorage» مجاني؟
نعم — نص درس «حفظ الحالة في localStorage» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Next.js 15 Fullstack (App Router + Server Actions)، انتقل إلى CoddyKit PRO. تتضمن دورة Next.js 15 Fullstack (App Router + Server Actions) 4 دروس في المجموع.
ماذا ستتعلم في «حفظ الحالة في localStorage»؟
حافظ على حالة العميل بعد إعادة تحميل الصفحات عبر حفظها في localStorage، ومعالجة hydration بأمان في Next.js، واستخدام middleware باسم persist في Zustand. تتمرن على Next.js 15 Fullstack (App Router + Server Actions) مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ Next.js 15 Fullstack (App Router + Server Actions)؟
لا تُشترط خبرة سابقة. Next.js 15 Fullstack (App Router + Server Actions) على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 4 من أصل 4.
كم من الوقت يستغرق درس «حفظ الحالة في localStorage»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس Next.js 15 Fullstack (App Router + Server Actions) هذا؟
نعم. كل درس في Next.js 15 Fullstack (App Router + Server Actions) يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- React Context API
- الحالة العامة باستخدام Zustand
- إدارة حالة الخادم
- حفظ الحالة في localStorage