-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseLocalStorageState.js
More file actions
39 lines (30 loc) · 1.11 KB
/
useLocalStorageState.js
File metadata and controls
39 lines (30 loc) · 1.11 KB
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
33
34
35
36
37
38
39
import { useState, useEffect, useRef } from "react";
/**
* localStorage hook for setting and updating localStorage state
*
* @param {string} localStorage key
* @param {any} initialState value
* @returns [state, updater]
*/
function useLocalStorageState(key, initialState) {
const [state, setState] = useState(() => {
const valueInLocalStorage = window.localStorage.getItem(key);
if (valueInLocalStorage) {
return JSON.parse(valueInLocalStorage)
}
// if a function is passed, call it to get the return value
return typeof initialState === 'function' ? initialState() : initialState;
});
// keep state of key so if it changes we can reference this value for comparison
const previousKeyRef = useRef(key);
useEffect(() => {
const previousKey = previousKeyRef.current;
// if the key value has changed, remove the previous item from local storage
if (previousKey !== key) {
window.localStorage.removeItem(previousKey);
}
localStorage.setItem(key, JSON.stringify(state));
}, [key, state]);
return [state, setState];
}
export default useLocalStorageState;