Last active
June 9, 2023 08:00
-
-
Save SheryConcepts/36e2042e2c1d955c2aafbc18db3e63db to your computer and use it in GitHub Desktop.
React hook for localStorage. Has the same interface as useState.
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 { useEffect, useState } from "react"; | |
export function useLocalStorage<T>(key: string, initialValue: T) { | |
const [state, setState] = useState<T>(() => { | |
const json = localStorage.getItem(key); | |
return json ? JSON.parse(json) : initialValue; | |
}); | |
// a wrapper over setState, but it also save given value to localStorage | |
function setStorage(value: T | ((v: T) => T)) { | |
const data = value instanceof Function ? value(state) : value; | |
const json = JSON.stringify(data); | |
localStorage.setItem(key, json); | |
setState(data); | |
} | |
return [state, setStorage] as const; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment