Created
March 21, 2023 11:25
-
-
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.
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, 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