localStorage에 상태 저장
상태를 localStorage에 저장하고 Next.js에서 하이드레이션을 안전하게 처리하며 Zustand의 persist 미들웨어를 사용해 페이지를 새로 고쳐도 클라이언트 상태를 유지합니다.
localStorage에 상태 저장은(는) CoddyKit의 무료 Next.js 15 Fullstack (App Router + Server Actions) 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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.
AI 튜터와 함께 TypeScript을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 22
- 레슨
- 88
자주 묻는 질문
“localStorage에 상태 저장” 강의는 무료인가요?
네 — “localStorage에 상태 저장” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Next.js 15 Fullstack (App Router + Server Actions) 강의 전체를 잠금 해제할 수 있습니다. Next.js 15 Fullstack (App Router + Server Actions) 강의에는 총 4개의 강의가 포함되어 있습니다.
“localStorage에 상태 저장”에서 뭘 배우나요?
상태를 localStorage에 저장하고 Next.js에서 하이드레이션을 안전하게 처리하며 Zustand의 persist 미들웨어를 사용해 페이지를 새로 고쳐도 클라이언트 상태를 유지합니다. 브라우저에서 직접 실행하는 실습 코드로 Next.js 15 Fullstack (App Router + Server Actions)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Next.js 15 Fullstack (App Router + Server Actions)을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Next.js 15 Fullstack (App Router + Server Actions)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“localStorage에 상태 저장” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Next.js 15 Fullstack (App Router + Server Actions) 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Next.js 15 Fullstack (App Router + Server Actions) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- React Context API
- Zustand를 활용한 전역 상태
- 서버 상태 관리
- localStorage에 상태 저장