0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

localStorage完全ガイド - ブラウザにデータを保存する方法

Last updated at Posted at 2025-11-19

localStorageとは

localStorageは、Webブラウザにデータを永続的に保存できるAPIです。ページを閉じても、ブラウザを再起動してもデータが残ります。

基本的な使い方

1. データの保存

localStorage.setItem('key', 'value');

2. データの取得

const value = localStorage.getItem('key');
console.log(value); // 'value'

3. データの削除

// 特定のキーを削除
localStorage.removeItem('key');

// 全データを削除
localStorage.clear();

4. キーの存在確認

if (localStorage.getItem('key') !== null) {
  console.log('データが存在します');
}

オブジェクトの保存

localStorageは文字列しか保存できません。オブジェクトや配列はJSONに変換する必要があります。

// オブジェクトを保存
const user = { name: 'Taro', age: 25 };
localStorage.setItem('user', JSON.stringify(user));

// オブジェクトを取得
const savedUser = localStorage.getItem('user');
const user = savedUser ? JSON.parse(savedUser) : null;
console.log(user); // { name: 'Taro', age: 25 }

React/Next.jsでの使用例

Todoリストアプリ

'use client';
import { useState, useEffect } from 'react';

export default function TodoApp() {
  const [todos, setTodos] = useState<string[]>([]);

  // 初回読み込み時にlocalStorageから取得
  useEffect(() => {
    const saved = localStorage.getItem('todos');
    if (saved) {
      setTodos(JSON.parse(saved));
    }
  }, []);

  // todosが変更されるたびにlocalStorageに保存
  useEffect(() => {
    localStorage.setItem('todos', JSON.stringify(todos));
  }, [todos]);

  const addTodo = (text: string) => {
    setTodos([...todos, text]);
  };

  return (
    <div>
      {/* UI */}
    </div>
  );
}

localStorageの制限

項目 制限内容
容量 約5-10MB(ブラウザによる)
データ型 文字列のみ
有効期限 無期限(手動削除まで残る)
スコープ 同じドメイン内のみ
セキュリティ 暗号化なし

注意点

❌ localStorageに保存してはいけないもの

  • パスワード
  • クレジットカード情報
  • 個人を特定できる機密情報
  • APIキー・トークン(可能な限り避ける)

⚠️ SSR(Server-Side Rendering)での注意

Next.jsなどでは、サーバーサイドでlocalStorageを使うとエラーになります。

// ❌ エラーになる
const value = localStorage.getItem('key');

// ✅ クライアントサイドでのみ実行
useEffect(() => {
  const value = localStorage.getItem('key');
}, []);

// ✅ または条件分岐
if (typeof window !== 'undefined') {
  const value = localStorage.getItem('key');
}

localStorage vs sessionStorage

localStorage sessionStorage
保持期間 無期限 タブを閉じるまで
スコープ 同じドメイン全体 同じタブのみ
用途 設定、Todo等 一時的なデータ
// sessionStorageの使い方はlocalStorageと同じ
sessionStorage.setItem('key', 'value');
const value = sessionStorage.getItem('key');

よくある使用例

1. ダークモード設定の保存

// 保存
localStorage.setItem('theme', 'dark');

// 取得
const theme = localStorage.getItem('theme') || 'light';

2. フォーム入力の一時保存

// 入力中に自動保存
input.addEventListener('input', (e) => {
  localStorage.setItem('draft', e.target.value);
});

// ページ読み込み時に復元
window.addEventListener('load', () => {
  const draft = localStorage.getItem('draft');
  if (draft) input.value = draft;
});

3. 訪問回数のカウント

let count = parseInt(localStorage.getItem('visitCount') || '0');
count++;
localStorage.setItem('visitCount', count.toString());
console.log(`${count}回目の訪問です`);

まとめ

  • localStorageはシンプルで使いやすいブラウザストレージ
  • 小規模なアプリならDBは不要
  • 機密情報は保存しない
  • SSR環境ではuseEffect内で使用
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?