useLocalStorage

useLocalStorage (로컬 스토리지 상태)

useLocalStorage 훅은 localStorage 값을 React 상태로 노출하고, 열린 탭 간에 상태를 동기화해요.

출처: 문서

본문

useLocalStorage 훅은 localStorage의 값을 React 상태로 사용할 수 있게 해줘요. 이 훅은 useState와 같은 방식으로 동작하지만 값을 localStorage에도 기록해요.

import { useLocalStorage } from '@mantine/hooks';

// The hook will read the value from localStorage.getItem('color-scheme')
// If localStorage is not available or the value at a given key does not exist,
// 'dark' will be assigned to the value variable
const [value, setValue] = useLocalStorage<string>({
  key: 'color-scheme',
  defaultValue: 'dark',
});

// The value is set both to state and localStorage at 'color-scheme'
setValue('light');

// You can also use a callback like in the useState hook to set the value
setValue((current) => (current === 'dark' ? 'light' : 'dark'));

값 제거 (Remove value)

removeValue 콜백을 사용해 localStorage/sessionStorage를 정리할 수 있어요. 값을 제거하면 defaultValue로 재설정돼요.

import { useLocalStorage } from '@mantine/hooks';

const [value, setValue, removeValue] = useLocalStorage<string>({
  key: 'color-scheme',
  defaultValue: 'light',
});

브라우저 탭 동기화 (Browser tabs synchronization)

useLocalStorage는 storage 이벤트를 구독해요. 한 탭에서 상태가 변경되면 열려 있는 다른 모든 브라우저 탭의 값을 자동으로 업데이트해요. Mantine 문서를 두 탭에 나란히 열고 색상 스킴(오른쪽 위 버튼, macOS의 ⌘ + J 또는 Windows/Linux의 Ctrl + J)을 변경해 이 기능을 테스트할 수 있어요.

JSON 직렬화/역직렬화 (Serialize/deserialize JSON)

기본적으로 이 훅은 JSON.stringify/JSON.parse로 데이터를 직렬화/역직렬화해요. JSON.stringify로 직렬화할 수 없는 데이터를 로컬 스토리지에 저장해야 한다면 직접 직렬화 핸들러를 제공하세요.

import { useLocalStorage } from '@mantine/hooks';

const [value, setValue] = useLocalStorage<string>({
  key: 'color-scheme',
  serialize: (value) => {
    /* return value serialized to string */
  },
  deserialize: (localStorageValue) => {
    /* parse localStorage string value and return value */
  },
});

superjson과 사용하기 (Usage with superjson)

superjson은 JSON.stringify/JSON.parse와 호환되지만 Date, Map, Set, BigInt에서도 동작해요.

import superjson from 'superjson';
import { useLocalStorage } from '@mantine/hooks';

const defaultValue = { name: 'John', age: 25 };

const [value, setValue] = useLocalStorage({
  key: 'data',
  defaultValue,
  serialize: superjson.stringify,
  deserialize: (str) =>
    str === undefined ? defaultValue : superjson.parse(str),
});

useSessionStorage

useSessionStorage 훅은 useLocalStorage 훅과 같은 방식으로 동작하지만 window.localStorage 대신 sessionStorage를 사용해요.

import { useSessionStorage } from '@mantine/hooks';

const [value, setValue] = useSessionStorage({
  key: 'session-key',
  defaultValue: 'mantine',
});

값 타입 설정 (Set value type)

useState 훅과 같은 방식으로 값 타입을 지정할 수 있어요.

import { useLocalStorage } from '@mantine/hooks';

const [value, setValue] = useLocalStorage<string>({
  key: 'color-scheme',
  defaultValue: 'light',
});

스토리지 값 읽기 (Read storage value)

훅 없이 스토리지에서 값을 읽으려면 readLocalStorageValue/readSessionStorageValue 함수를 사용해요. 이 함수들은 useLocalStorage/useSessionStorage 훅과 같은 인자를 받아요.

import { readLocalStorageValue } from '@mantine/hooks';

const value = readLocalStorageValue({ key: 'color-scheme' });

정의 (Definition)

interface UseStorageOptions<T> {
  /** Local storage key */
  key: string;
  /** Default value that will be set if value is not found in local storage */
  defaultValue?: T;
  /** If set to true, value will be updated in useEffect after mount. Default value is true. */
  getInitialValueInEffect?: boolean;
  /** Determines whether the value must be synced between browser tabs, `true` by default */
  sync?: boolean;
  /** Function to serialize value into a string to be saved in local storage */
  serialize?: (value: T) => string;
  /** Function to deserialize string value from local storage to value */
  deserialize?: (value: string) => T;
}

type UseStorageReturnValue<T> = [
  T, // current value
  (val: T | ((prevState: T) => T)) => void, // callback to set value in storage
  () => void, // callback to remove value from storage
];

function useLocalStorage<T>(
  options: UseStorageOptions<T>,
): UseStorageReturnValue<T>;

Exported types

UseStorageOptions와 UseStorageReturnValue 타입은 @mantine/hooks 패키지에서 내보내져요.

import type { UseStorageOptions, UseStorageReturnValue } from '@mantine/hooks';

더 알아보기 (Learn more)