Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useLocalStorage.js

39 lines1.3 KB

1import * as React from 'react'
2export default function useLocalStorage(key, initialValue) {
3 // State to store our value
4 // Pass initial state function to useState so logic is only executed once
5 const [storedValue, setStoredValue] = React.useState(() => {
6 if (typeof window !== 'undefined') {
7 const item = window.localStorage.getItem(key)
8 try {
9 // Get from local storage by key
10 // Parse stored json or if none return initialValue
11 return item ? JSON.parse(item) : initialValue
12 } catch (error) {
13 return item
14 }
15 }
16 return initialValue
17 })
18 // Return a wrapped version of useState's setter function that ...
19 // ... persists the new value to localStorage.
20 const setValue = React.useCallback(
21 value => {
22 try {
23 // Allow value to be a function so we have same API as useState
24 // Save state
25 setStoredValue(newStoredValue => {
26 const valueToStore =
27 value instanceof Function ? value(newStoredValue) : value
28 window.localStorage.setItem(key, JSON.stringify(valueToStore))
29 return valueToStore
30 })
31 // Save to local storage
32 } catch (error) {
33 // A more advanced implementation would handle the error case
34 }
35 },
36 [key]
37 )
38 return [storedValue, setValue]