Skip to content

Instantly share code, notes, and snippets.

@sandroweb
Last active January 11, 2024 22:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sandroweb/996bdae8cb8816a841d69e52524abb7c to your computer and use it in GitHub Desktop.
Save sandroweb/996bdae8cb8816a841d69e52524abb7c to your computer and use it in GitHub Desktop.
A React Hook to manage LocalStorage items with generic type, with set, refresh and remove actions.
import { useCallback, useMemo, useState } from 'react';
export interface useLocalStorageProps<T> {
id: string;
defaultValue: T;
}
export interface useLocalStorageReturn<T> {
setValue: (value: T) => void;
value: T;
refresh: () => void;
remove: () => void;
}
export const useLocalStorage = <T>({
id,
defaultValue,
}: useLocalStorageProps<T>): useLocalStorageReturn<T> => {
const [localStorageValue, setLocalStorageValue] = useState<
string | undefined
>(window.localStorage.getItem(id) || undefined);
const refresh = useCallback(() => {
return setLocalStorageValue(
window.localStorage.getItem(id) || undefined,
);
}, [id]);
const setValue = useCallback(
(value: T) => {
if (value) {
window.localStorage.setItem(id, JSON.stringify(value));
refresh();
}
},
[id, refresh],
);
const remove = useCallback(() => {
window.localStorage.removeItem(id);
return refresh();
}, [id, refresh]);
const value = useMemo<T>(() => {
return localStorageValue ? JSON.parse(localStorageValue) : defaultValue;
}, [localStorageValue, defaultValue]);
return {
setValue,
value,
refresh,
remove,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment