코드도보통지

3관문. useLocalStorage

관문 3 / 7

상태 변경 시 localStorage와 자동 동기화되는 useLocalStorage 훅을 구현하라.

📖 이론 비급

useLocalStorage: 영속 상태

useState의 drop-in 교체처럼 동작하면서 localStorage에 자동 저장/복원한다.

주의사항:

  • 초기화 시 Lazy Initialization으로 localStorage.getItem()을 한 번만 호출
  • SSR 환경에서 window가 없을 수 있으므로 방어 코드 필요
  • JSON 직렬화/역직렬화 오류 처리
  • 다른 탭에서의 변경은 storage 이벤트로 감지

⚔️ 수련 코드

import { useState, useEffect } from 'react';

// TODO: useLocalStorage 훅을 구현하라
// useState와 동일한 API: [value, setValue]
// Lazy Initialization으로 초기값을 localStorage에서 읽기
// setValue 시 localStorage에도 저장
function useLocalStorage(key, initialValue) {
}

export default function ThemeToggle() {
  const [theme, setTheme] = useLocalStorage('theme', 'light');

  return (
    <div style={{ background: theme === 'dark' ? '#222' : '#fff', color: theme === 'dark' ? '#fff' : '#000', padding: 24 }}>
      <p>현재 테마: {theme}</p>
      <button onClick={() => setTheme(t => t === 'light' ? 'dark' : 'light')}>
        전환
      </button>
      <p><small>새로고침해도 유지됩니다</small></p>
    </div>
  );
}