Created
June 1, 2023 09:59
-
-
Save akirco/fe61012dcf5a2c64723e39334f92c606 to your computer and use it in GitHub Desktop.
react hooks-useSafeLocalStorage
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"; | |
export function useSafeLocalStorage(key: string, initialValue: any) { | |
const [valueProxy, setValueProxy] = useState(() => { | |
try { | |
const value = window.localStorage.getItem(key); | |
return value ? JSON.parse(value) : initialValue; | |
} catch { | |
return initialValue; | |
} | |
}); | |
useEffect(() => { | |
try { | |
window.localStorage.setItem(key, JSON.stringify(valueProxy)); | |
} catch {} | |
}, [key, valueProxy]); | |
const setValue = (value: any) => { | |
setValueProxy(value); | |
}; | |
return [valueProxy, setValue]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
你好