useReadLocalStorage()
This React Hook allows you to read a value from localStorage by its key. It can be useful if you just want to read without passing a default value.
If the window object is not present (as in SSR), or if the value doesn't exist, useReadLocalStorage()
will return null
.
Note:
If you want to be able to change the value, look useLocalStorage().
The Hook
1import { useCallback, useEffect, useState } from 'react'23import { useEventListener } from 'usehooks-ts'45type Value<T> = T | null67function useReadLocalStorage<T>(key: string): Value<T> {8 // Get from local storage then9 // parse stored json or return initialValue10 const readValue = useCallback((): Value<T> => {11 // Prevent build error "window is undefined" but keep keep working12 if (typeof window === 'undefined') {13 return null14 }1516 try {17 const item = window.localStorage.getItem(key)18 return item ? (JSON.parse(item) as T) : null19 } catch (error) {20 console.warn(`Error reading localStorage key “${key}”:`, error)21 return null22 }23 }, [key])2425 // State to store our value26 // Pass initial state function to useState so logic is only executed once27 const [storedValue, setStoredValue] = useState<Value<T>>(readValue)2829 // Listen if localStorage changes30 useEffect(() => {31 setStoredValue(readValue())32 // eslint-disable-next-line react-hooks/exhaustive-deps33 }, [])3435 const handleStorageChange = useCallback(36 (event: StorageEvent | CustomEvent) => {37 if ((event as StorageEvent)?.key && (event as StorageEvent).key !== key) {38 return39 }40 setStoredValue(readValue())41 },42 [key, readValue],43 )4445 // this only works for other documents, not the current one46 useEventListener('storage', handleStorageChange)4748 // this is a custom event, triggered in writeValueToLocalStorage49 // See: useLocalStorage()50 useEventListener('local-storage', handleStorageChange)5152 return storedValue53}5455export default useReadLocalStorage
Usage
1import { useReadLocalStorage } from 'usehooks-ts'23export default function Component() {4 // Assuming a value was set in localStorage with this key5 const darkMode = useReadLocalStorage('darkMode')67 return <p>DarkMode is {darkMode ? 'enabled' : 'disabled'}</p>8}
See a way to make this page better?
Edit there »