Created
October 3, 2025 21:48
-
-
Save thanhnguyen2187/44aa26be943320f2c36021b867e65c75 to your computer and use it in GitHub Desktop.
Inspired by https://userunes.com/uselocalstorage. Added typing for value.
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 { 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