aboutsummaryrefslogtreecommitdiffstats
path: root/src/hooks/useLocalStorage.js
blob: 6dbed36f8d2ad93ba28b0ede11c975e96c301dbb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { useState } from "react";

const useLocalStorage = (key, initialValue) => {
  const storedVal = localStorage[key]
    ? JSON.parse(localStorage[key]) || initialValue
    : initialValue;
  const [value, setValue] = useState(storedVal);

  function update(newValue) {
    localStorage[key] = JSON.stringify(newValue);
    setValue(newValue);
  }

  return [value, update];
};

export default useLocalStorage;