Created
April 5, 2025 20:20
-
-
Save acquitelol/e4e2a0f6f938913d4bf6ea3514947e41 to your computer and use it in GitHub Desktop.
A hook which acts exactly like useState but also syncs a value in `localStorage`.
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 { useState, useLayoutEffect } from "react"; | |
| export const useStorageValue = <T>( | |
| key: string, | |
| def: string | null = null, | |
| replacer: (x: string) => T, | |
| reviver?: (x: T) => string, | |
| ) => { | |
| const [value, setValue] = useState<T>( | |
| replacer(localStorage.getItem(key) ?? def!), | |
| ); | |
| useLayoutEffect(() => { | |
| localStorage.setItem(key, (reviver ?? String)(value)); | |
| // eslint-disable-next-line react-hooks/exhaustive-deps | |
| }, [value]); | |
| return [value, setValue] as const; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment