useLocalStorage()

Persist the state with local storage so that it remains after a page refresh. This can be useful for a dark theme or to record session information. This hook is used in the same way as useState except that you must pass the storage key in the 1st parameter. If the window object is not present (as in SSR), useLocalStorage() will return the default value.

Side notes:

The Hook

1import {
2 Dispatch,
3 SetStateAction,
4 useCallback,
5 useEffect,
6 useRef,
7 useState,
8} from 'react'
9
10// See: https://usehooks-ts.com/react-hook/use-event-listener
11import { useEventListener } from '../useEventListener'
12
13declare global {
14 interface WindowEventMap {
15 'local-storage': CustomEvent
16 }
17}
18
19type SetValue<T> = Dispatch<SetStateAction<T>>
20
21function useLocalStorage<T>(key: string, initialValue: T): [T, SetValue<T>] {
22 // Get from local storage then
23 // parse stored json or return initialValue
24 const readValue = useCallback((): T => {
25 // Prevent build error "window is undefined" but keep keep working
26 if (typeof window === 'undefined') {
27 return initialValue
28 }
29
30 try {
31 const item = window.localStorage.getItem(key)
32 return item ? (parseJSON(item) as T) : initialValue
33 } catch (error) {
34 console.warn(`Error reading localStorage key “${key}”:`, error)
35 return initialValue
36 }
37 }, [initialValue, key])
38
39 // State to store our value
40 // Pass initial state function to useState so logic is only executed once
41 const [storedValue, setStoredValue] = useState<T>(readValue)
42
43 const setValueRef = useRef<SetValue<T>>()
44
45 setValueRef.current = value => {
46 // Prevent build error "window is undefined" but keeps working
47 if (typeof window == 'undefined') {
48 console.warn(
49 `Tried setting localStorage key “${key}” even though environment is not a client`,
50 )
51 }
52
53 try {
54 // Allow value to be a function so we have the same API as useState
55 const newValue = value instanceof Function ? value(storedValue) : value
56
57 // Save to local storage
58 window.localStorage.setItem(key, JSON.stringify(newValue))
59
60 // Save state
61 setStoredValue(newValue)
62
63 // We dispatch a custom event so every useLocalStorage hook are notified
64 window.dispatchEvent(new Event('local-storage'))
65 } catch (error) {
66 console.warn(`Error setting localStorage key “${key}”:`, error)
67 }
68 }
69
70 // Return a wrapped version of useState's setter function that ...
71 // ... persists the new value to localStorage.
72 const setValue: SetValue<T> = useCallback(
73 value => setValueRef.current?.(value),
74 [],
75 )
76
77 useEffect(() => {
78 setStoredValue(readValue())
79 // eslint-disable-next-line react-hooks/exhaustive-deps
80 }, [])
81
82 const handleStorageChange = useCallback(() => {
83 setStoredValue(readValue())
84 }, [readValue])
85
86 // this only works for other documents, not the current one
87 useEventListener('storage', handleStorageChange)
88
89 // this is a custom event, triggered in writeValueToLocalStorage
90 // See: useLocalStorage()
91 useEventListener('local-storage', handleStorageChange)
92
93 return [storedValue, setValue]
94}
95
96export default useLocalStorage
97
98// A wrapper for "JSON.parse()"" to support "undefined" value
99function parseJSON<T>(value: string | null): T | undefined {
100 try {
101 return value === 'undefined' ? undefined : JSON.parse(value ?? '')
102 } catch {
103 console.log('parsing error on', { value })
104 return undefined
105 }
106}

Usage

1import React from 'react'
2
3import { useLocalStorage } from 'usehooks-ts'
4
5// Usage
6export default function Component() {
7 const [isDarkTheme, setDarkTheme] = useLocalStorage('darkTheme', true)
8
9 const toggleTheme = () => {
10 setDarkTheme(prevValue => !prevValue)
11 }
12
13 return (
14 <button onClick={toggleTheme}>
15 {`The current theme is ${isDarkTheme ? `dark` : `light`}`}
16 </button>
17 )
18}

Edit on CodeSandbox

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