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, useLocalStorage() will return null.

Note:

If you want to be able to change the value, look useLocalStorage().

The Hook

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

Usage

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

Edit on CodeSandbox

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