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

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 »