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'
2
3import { useEventListener } from 'usehooks-ts'
4
5type Value<T> = T | null
6
7function useReadLocalStorage<T>(key: string): Value<T> {
8 // Get from local storage then
9 // parse stored json or return initialValue
10 const readValue = useCallback((): Value<T> => {
11 // Prevent build error "window is undefined" but keep keep working
12 if (typeof window === 'undefined') {
13 return null
14 }
15
16 try {
17 const item = window.localStorage.getItem(key)
18 return item ? (JSON.parse(item) as T) : null
19 } catch (error) {
20 console.warn(`Error reading localStorage key “${key}”:`, error)
21 return null
22 }
23 }, [key])
24
25 // State to store our value
26 // Pass initial state function to useState so logic is only executed once
27 const [storedValue, setStoredValue] = useState<Value<T>>(readValue)
28
29 // Listen if localStorage changes
30 useEffect(() => {
31 setStoredValue(readValue())
32 // eslint-disable-next-line react-hooks/exhaustive-deps
33 }, [])
34
35 const handleStorageChange = useCallback(
36 (event: StorageEvent | CustomEvent) => {
37 if ((event as StorageEvent)?.key && (event as StorageEvent).key !== key) {
38 return
39 }
40 setStoredValue(readValue())
41 },
42 [key, readValue],
43 )
44
45 // this only works for other documents, not the current one
46 useEventListener('storage', handleStorageChange)
47
48 // this is a custom event, triggered in writeValueToLocalStorage
49 // See: useLocalStorage()
50 useEventListener('local-storage', handleStorageChange)
51
52 return storedValue
53}
54
55export default useReadLocalStorage

Usage

1import { useReadLocalStorage } from 'usehooks-ts'
2
3export default function Component() {
4 // Assuming a value was set in localStorage with this key
5 const darkMode = useReadLocalStorage('darkMode')
6
7 return <p>DarkMode is {darkMode ? 'enabled' : 'disabled'}</p>
8}

Edit on CodeSandbox

See a way to make this page better?
Edit there »