Created
December 2, 2023 22:29
-
-
Save deeamtee/16b7848fa130de33a63933a705947143 to your computer and use it in GitHub Desktop.
This file contains hidden or 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, Dispatch, SetStateAction } from 'react' | |
| function isDefined (storedValue: string | null): boolean { | |
| return storedValue !== null && storedValue !== 'undefined'; | |
| } | |
| export function useLocalStorageState<T>( | |
| key: string, | |
| initialValue: T | |
| ): [T, Dispatch<SetStateAction<T>>] { | |
| const [state, setState] = useState<T>(() => { | |
| const storedValue = localStorage.getItem(key) | |
| return isDefined(storedValue) ? (JSON.parse(storedValue!) as T) : initialValue | |
| }) | |
| useEffect(() => { | |
| localStorage.setItem(key, JSON.stringify(state)) | |
| }, [key, state]) | |
| return [state, setState] | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment