Skip to content

Instantly share code, notes, and snippets.

@acquitelol
Created April 5, 2025 20:20
Show Gist options
  • Select an option

  • Save acquitelol/e4e2a0f6f938913d4bf6ea3514947e41 to your computer and use it in GitHub Desktop.

Select an option

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`.
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