Skip to content

Instantly share code, notes, and snippets.

@simenbrekken-visma
Created February 16, 2023 18:51
Show Gist options
  • Save simenbrekken-visma/b1c9215a7d06a041aa2ca84af66e661d to your computer and use it in GitHub Desktop.
Save simenbrekken-visma/b1c9215a7d06a041aa2ca84af66e661d to your computer and use it in GitHub Desktop.
useLocalStorage
export function getLocalStorageItem<T>(key: string, initialValue: T): T {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.warn(`Could not get localStorage key "${key}"`, error);
return initialValue;
}
}
export function setLocalStorageItem<T>(
key: string,
value: T | null | undefined
): void {
if (value === null || value === undefined) {
try {
window.localStorage.removeItem(key);
} catch (error) {
console.warn(`Could not remove localStorage key "${key}"`, error);
}
} else {
try {
window.localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.warn(`Could not set localStorage key "${key}"`, error);
}
}
}
import { useCallback } from 'react';
import { getLocalStorageItem, setLocalStorageItem } from '../utils/storage';
type SetValue<T> = (
value: T | null | undefined | ((prevValue: T) => T)
) => void;
type UseLocalStorageReturn<T> = [T, SetValue<T>];
export function useLocalStorage<T = unknown>(
key: string,
initialValue: T
): UseLocalStorageReturn<T> {
const value = getLocalStorageItem<T>(key, initialValue);
const setValue = useCallback<SetValue<T>>(
(value) => {
if (value instanceof Function) {
setLocalStorageItem(
key,
value(getLocalStorageItem(key, initialValue))
);
} else {
setLocalStorageItem(key, value);
}
},
[key, initialValue]
);
return [value, setValue];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment