Skip to content

Instantly share code, notes, and snippets.

@thanhnguyen2187
Created October 3, 2025 21:48
Show Gist options
  • Save thanhnguyen2187/44aa26be943320f2c36021b867e65c75 to your computer and use it in GitHub Desktop.
Save thanhnguyen2187/44aa26be943320f2c36021b867e65c75 to your computer and use it in GitHub Desktop.
Inspired by https://userunes.com/uselocalstorage. Added typing for value.
import { onMount } from "svelte";
const useLocalStorage = <T>(key: string, initialValue: T) => {
let value = $state<T>(initialValue);
onMount(() => {
const currentValue = localStorage.getItem(key);
if (currentValue) value = JSON.parse(currentValue);
});
$effect(() => {
save();
});
const save = () => {
if (value) {
localStorage.setItem(key, JSON.stringify(value));
} else {
localStorage.removeItem(key);
}
};
return {
get value(): T {
return value;
},
set value(v: T) {
value = v;
},
};
};
export default useLocalStorage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment