Created
June 12, 2020 12:21
-
-
Save haggen/324170b0f7391b9c1d42b4b82e4dc266 to your computer and use it in GitHub Desktop.
TypeScript Local Storage backed state hook for React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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