Skip to content

Instantly share code, notes, and snippets.

@doubleedesign
Created March 21, 2023 11:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save doubleedesign/6a6af9c65080d2b41718598cbb510f9e to your computer and use it in GitHub Desktop.
Save doubleedesign/6a6af9c65080d2b41718598cbb510f9e to your computer and use it in GitHub Desktop.
useLocalStorage React hook. Keep a state value in sync with one cached in the browser using local storage.
import { useState, useEffect, Dispatch, SetStateAction } from 'react';
export function useLocalStorage<T>(key: string, defaultValue: T): { value: T; setValue: Dispatch<SetStateAction<T>> } {
const [value, setValue] = useState(() => {
return localStorage?.getItem(key) ? JSON.parse(localStorage.getItem(key)) : defaultValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return { value, setValue };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment