Skip to content

Instantly share code, notes, and snippets.

@ChrisCrossCrash
Last active November 25, 2021 07:18
Show Gist options
  • Save ChrisCrossCrash/ef8b6e9fe468bc8ee977c65cfb05e7a6 to your computer and use it in GitHub Desktop.
Save ChrisCrossCrash/ef8b6e9fe468bc8ee977c65cfb05e7a6 to your computer and use it in GitHub Desktop.
A custom hook for putting anything that can be JSON encoded and decoded into local storage. IMPORTANT: Do not use more than one `useLocalStorage` hook for the same local storage key. This will cause the local storage to update, but not the states for BOTH hooks.
import * as React from 'react'
import {useEffect} from 'react'
type Jsonable = null | boolean | number | string | Jsonable[] | { [prop: string]: Jsonable }
export const useLocalStorage = <T extends Jsonable>(
key: string,
initialValue: T | (() => T),
) => {
const [value, setValue] = React.useState(() => {
// First, check if there is already a value for the provided key.
const storedValue = localStorage.getItem(key)
if (typeof storedValue === 'string') {
return JSON.parse(storedValue) as T
}
// If there isn't already a stored value, use the initialValue.
let returnValue
initialValue instanceof Function
? returnValue = initialValue()
: returnValue = initialValue
return returnValue
})
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value))
}, [key, value])
return [value, setValue] as const
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment