Skip to content

Instantly share code, notes, and snippets.

@maxandron
Last active November 29, 2022 02:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxandron/fee0d8034e686fdac2383b04b8d7775a to your computer and use it in GitHub Desktop.
Save maxandron/fee0d8034e686fdac2383b04b8d7775a to your computer and use it in GitHub Desktop.
useLocalStorage - an example of a hook the retrieves and stores data in local storage asynchronously
import { useEffect, useState } from "react"
export function useLocalStorage(key: string) {
const [value, setValue] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(true)
useEffect(function getInitialValue() {
setValue(localStorage.getItem(key))
setIsLoading(false)
}, [])
useEffect(function updateLocalStorage() {
if (value !== null)
localStorage.setItem(key, value)
}, [value])
return [value, setValue, isLoading] as const
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment