カスタムHooksを活用してローカルストレージにデータを永続化する方法
概要
Reactアプリケーションでローカルストレージを使用してデータを永続化することは一般的な要求です。この記事では、カスタムHooksを活用してローカルストレージにデータを保存・読み込みする方法について解説します。これにより、ページをリロードしてもデータが保持されるようになります。
なぜこの技術/パターンが必要なのか
一度入力したデータを保持しておくことで、ユーザーエクスペリエンスを向上させることができます。例えば、フォームの入力値やユーザーの設定などをローカルストレージに保存しておくことで、再度入力する手間を省くことができます。
解決する問題やユースケース
- ページをリロードしてもデータを保持したい場合
- ユーザーが入力した情報を保持しておきたい場合
前提知譆と必要な依存関係
- React Hooksの基本知識
- JavaScriptの基本知識
基本実装
import React, { useState, useEffect } from 'react';
const UseLocalStorage = (key, initialValue) => {
const [storedValue, setStoredValue] = useState(() => {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
});
const setValue = value => {
setStoredValue(value);
window.localStorage.setItem(key, JSON.stringify(value));
};
return [storedValue, setValue];
};
// 使用例
const ExampleComponent = () => {
const [name, setName] = UseLocalStorage('name', '');
return (
<input
type="text"
value={name}
onChange={e => setName(e.target.value)}
/>
);
};
export default ExampleComponent;
TypeScript型定義
interface Props {
// プロップスの型定義
}
interface State {
// ステートの型定義
}
テストコード
import { render, screen, fireEvent } from '@testing-library/react';
import ExampleComponent from './ExampleComponent';
test('should render correctly', () => {
render(<ExampleComponent />);
// テストケース
});
パフォーマンス最適化
ローカルストレージへのアクセスは非同期で行われるため、パフォーマンス面で注意が必要です。余分なアクセスを避けるために、必要最小限のデータのみを保存するようにしましょう。
実践的な応用例
// ユーザーのテーマ設定をローカルストレージに保存する例
const [theme, setTheme] = UseLocalStorage('theme', 'light');
関連技術・参考情報
- [React Custom Hooks](https://reactjs.org/docs/hooks-custom.html)
- [useEffect Hook](https://reactjs.org/docs/hooks-effect.html)
- [localStorage MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)
- [React.memo](https://reactjs.org/docs/react-api.html#reactmemo)
- [useMemo](https://reactjs.org/docs/hooks-reference.html#usememo)
- [useCallback](https://reactjs.org/docs/hooks-reference.html#usecallback)
この記事では、ReactのカスタムHooksを活用してローカルストレージにデータを永続化する方法を実際のコードとともに紹介しました。ローカルストレージを使うことで、ユーザー体験を向上させることができるので、是非活用してみてください。