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

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