Created
August 29, 2022 12:58
-
-
Save mewisme/45ed97ed0743cc47f57471848d1d8c63 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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