-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusePersistentState.js
More file actions
23 lines (19 loc) · 697 Bytes
/
usePersistentState.js
File metadata and controls
23 lines (19 loc) · 697 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { useState, useEffect } from 'react';
import * as LocalStorageManager from '../utils/LocalStorageManager';
/**
* A custom hook that uses useState and persists the state to localStorage.
*
* @param {string} key The key to use in localStorage.
* @param {*} defaultValue The default value to use if nothing is in localStorage.
* @returns A stateful value, and a function to update it.
*/
const usePersistentState = (key, defaultValue) => {
const [state, setState] = useState(() =>
LocalStorageManager.get(key, defaultValue),
);
useEffect(() => {
LocalStorageManager.set(key, state);
}, [key, state]);
return [state, setState];
};
export default usePersistentState;