Skip to content

Instantly share code, notes, and snippets.

@haggen
Created June 12, 2020 12:21
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 haggen/324170b0f7391b9c1d42b4b82e4dc266 to your computer and use it in GitHub Desktop.
Save haggen/324170b0f7391b9c1d42b4b82e4dc266 to your computer and use it in GitHub Desktop.
TypeScript Local Storage backed state hook for React
import { useState, useEffect } from "react";
type Serializable =
| null
| boolean
| number
| string
| Date
| { toJSON(): string }
| Serializable[]
| { [key: string]: Serializable };
export default function useLocalStoredState(
key: string,
defaultValue?: Serializable
) {
const storedValue = localStorage.getItem(key);
const [value, setValue] = useState(
storedValue !== null ? JSON.parse(storedValue) : 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