aboutsummaryrefslogtreecommitdiff
path: root/modern/src/common/usePersistedState.js
blob: a3a60d75c1e5ffe9775d5e0198f48b0d55266acc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { useEffect, useState } from 'react';

export const usePersistedState = (key, defaultValue) => {

  const [value, setValue] = useState(() => {
    const stickyValue = window.localStorage.getItem(key);
    return stickyValue ? JSON.parse(stickyValue) : defaultValue;
  });

  useEffect(() => {
    window.localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
};