-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusePersistentState.ts
More file actions
32 lines (28 loc) · 884 Bytes
/
usePersistentState.ts
File metadata and controls
32 lines (28 loc) · 884 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import React, { useEffect } from 'react'
/**
* Persist state using local storage.
* See https://bit.ly/31IIgND
*
* @param key the unique key for the object being stored
* @param defaultValue the default value for the state object
*/
export const usePersistentState = (
key: string,
defaultValue: unknown
): [unknown, React.Dispatch<unknown>] => {
const item = JSON.parse(localStorage.getItem(key)) || defaultValue
// use persisted state for an array only if its length
// is the same as the defaultValue length otherwise you
// may end up with an unpredictable state
const [state, setState] = React.useState(() =>
Array.isArray(item) && Array.isArray(defaultValue)
? item.length === defaultValue.length
? item
: defaultValue
: item
)
useEffect(() => {
localStorage.setItem(key, JSON.stringify(state))
}, [key, state])
return [state, setState]
}