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

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}

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