pashto-grammar/src/useStickyState.ts

17 lines
522 B
TypeScript
Raw Normal View History

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