RGB logo

RGB Studios.org

A web development company

January 4, 2024

How to Create a Svelte Kit Store That Syncs With Local Storage - Svelte 5

Justin Golden

Photo credit @joshstyle on Unsplash

Length: Short

Level: X Beginner ✓ Intermediate ✓ Advanced

The Solution

let todos = $state([]);

$effect(()=> {
  const savedTodos = localStorage.getItem('todos');
  if(savedTodos) todos = JSON.parse(savedTodos);

$effect(()=> {
  localStorage.setItem('todos', JSOn.stringify(todos);

The Explanation

The $effect code runs whenever there’s a change. Above, we get the localStorage item. We check if it exists and if so, we override our current value by parsing the JSON of the localStorage object. The second block will run whenever todos changes and stringifies the variable and stores it in localStorage. And of course, the first line declares our local todos variable with $state.

Check out Joy of Code’s Todo App With Svelte 5 Runes Video for more.

Full Solution With Support for Older Svelte

import { writable } from 'svelte/store';

export default function store(key, defaultValue) {
	const store = writable(defaultValue);

	function getValue() {
		store.set(JSON.parse(localStorage.getItem(key)) ?? defaultValue);

	if (typeof localStorage !== 'undefined') {

		window.addEventListener('storage', getValue);

		store.subscribe((val) => localStorage.setItem(key, JSON.stringify(val)));

	return store;

This is the solution that I’ve personally been using a variant of on many projects. Enjoy!

More Blog Articles
  Share   Tweet   Pin   Share   Post   Post   Share   Email