diff options
Diffstat (limited to 'modern/src/common/util/usePersistedState.js')
-rw-r--r-- | modern/src/common/util/usePersistedState.js | 18 |
1 files changed, 18 insertions, 0 deletions
diff --git a/modern/src/common/util/usePersistedState.js b/modern/src/common/util/usePersistedState.js new file mode 100644 index 00000000..8bc4401f --- /dev/null +++ b/modern/src/common/util/usePersistedState.js @@ -0,0 +1,18 @@ +import { useEffect, useState } from 'react'; + +export const savePersistedState = (key, value) => { + window.localStorage.setItem(key, JSON.stringify(value)); +}; + +export default (key, defaultValue) => { + const [value, setValue] = useState(() => { + const stickyValue = window.localStorage.getItem(key); + return stickyValue ? JSON.parse(stickyValue) : defaultValue; + }); + + useEffect(() => { + savePersistedState(key, value); + }, [key, value]); + + return [value, setValue]; +}; |