useLocalStorage

Sync state to local storage so that it persists through a page refresh. Usage is similar to useState except we pass in a local storage key so that we can default to that value on page load instead of the specified initial value.

Usage

useLocalStorage.ts
import { useState, useEffect } from 'react';

type StorageValue<T> = T | null;

interface StorageOptions<T> {
  key: string;
  defaultValue?: StorageValue<T>;
}

const useLocalStorage = <T>({
  key,
  defaultValue = null,
}: StorageOptions<T>): [StorageValue<T>, (value: T) => void] => {
  const [state, setState] = useState<StorageValue<T>>(() => {
    const storedValue = localStorage.getItem(key);
    if (storedValue !== null) {
      return JSON.parse(storedValue) as T;
    } else {
      return defaultValue;
    }
  });

  useEffect(() => {
    if (state === null) {
      localStorage.removeItem(key);
    } else {
      localStorage.setItem(key, JSON.stringify(state));
    }
  }, [key, state]);

  const setValue = (value: T) => {
    setState(value);
  };

  return [state, setValue];
};

export default useLocalStorage;

This useLocalStorage hook allows you to store and retrieve a value in local storage using the useState and useEffect hooks from React. It takes a key string as a parameter, which is used as the key for storing the value in local storage. It also takes an optional defaultValue parameter, which is used as the initial value if no value is stored in local storage.

The hook returns a tuple containing the current value and a function to set the value. When the value is updated, the hook automatically stores the new value in local storage using the useEffect hook.

Here's an example of how to use the useLocalStorage hook in a component:

import useLocalStorage from './useLocalStorage';

const MyComponent = () => {
  const [count, setCount] = useLocalStorage<number>({
    key: 'count',
    defaultValue: 0,
  });

  const handleIncrement = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleIncrement}>Increment</button>
    </div>
  );
};

In this example, we use the useLocalStorage hook to store a count value in local storage. We pass an object with the key and defaultValue options to the hook, and we destructure the returned tuple into count and setCount. We use count to display the current value, and setCount to update the value when the button is clicked.

Last updated