Skip to content

Instantly share code, notes, and snippets.

@mewisme
Created August 29, 2022 12:58
Show Gist options
  • Select an option

  • Save mewisme/45ed97ed0743cc47f57471848d1d8c63 to your computer and use it in GitHub Desktop.

Select an option

Save mewisme/45ed97ed0743cc47f57471848d1d8c63 to your computer and use it in GitHub Desktop.
import { Dispatch, SetStateAction, useEffect, useState } from "react";
interface StickyState<S> {
key: string,
defaultValue: S | (() => S),
}
export function useStickyState<S>({ defaultValue, key }: StickyState<S>): [S, Dispatch<SetStateAction<S>>] {
const [value, setValue] = useState<S>(defaultValue);
useEffect(() => {
const stickyValue = window.localStorage.getItem(key);
if (stickyValue !== null) {
setValue(JSON.parse(stickyValue));
}
}, [key]);
useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment