2021-09-18 13:31:05 +00:00
|
|
|
import { useEffect, useState } from "react";
|
|
|
|
|
2021-09-18 22:22:47 +00:00
|
|
|
export default function useStickyState<T>(defaultValue: T, key: string): {
|
|
|
|
value: T,
|
|
|
|
setValue: React.Dispatch<React.SetStateAction<T>>,
|
|
|
|
} {
|
2021-09-18 13:31:05 +00:00
|
|
|
|
2021-09-18 22:22:47 +00:00
|
|
|
const [value, setValue] = useState<T>(() => {
|
|
|
|
const stickyValue = window.localStorage.getItem(key);
|
|
|
|
return stickyValue !== null
|
|
|
|
? JSON.parse(stickyValue) as T
|
|
|
|
: defaultValue;
|
|
|
|
});
|
2021-09-18 13:31:05 +00:00
|
|
|
|
2021-09-18 22:22:47 +00:00
|
|
|
useEffect(() => {
|
|
|
|
window.localStorage.setItem(key, JSON.stringify(value));
|
|
|
|
}, [key, value]);
|
2021-09-18 13:31:05 +00:00
|
|
|
|
2021-09-18 22:22:47 +00:00
|
|
|
return {value, setValue};
|
2021-09-18 13:31:05 +00:00
|
|
|
}
|