Svelte Stores Writable Readable Derived Custom
Definisi
Store adalah wadah state yang bisa diakses dari mana saja (lintas komponen) lewat subscribe. Tiga bentuk bawaan: writable (bisa diubah), readable (hanya baca), derived (hasil dari store lain).
Kapan dipakai
Pakai store saat state butuh dibagi banyak komponen tanpa prop drilling, atau state hidup di luar tree komponen (misal tema, user login, counter global). Untuk state lokal cukup let di komponen.
Cara kerja
writable
// store.js
import { writable } from 'svelte/store';
export const count = writable(0);<script>
import { count } from './store.js';
function inc() { count.update(n => n + 1); }
</script>
<button on:click={inc}>{$count}</button>Tanda $ di depan nama store = auto-subscribe di template.
readable
import { readable } from 'svelte/store';
export const time = readable(new Date(), (set) => {
const id = setInterval(() => set(new Date()), 1000);
return () => clearInterval(id); // cleanup
});derived
import { derived } from 'svelte/store';
export const doubled = derived(count, ($c) => $c * 2);Custom store
function createCounter() {
const { subscribe, set, update } = writable(0);
return { subscribe, inc: () => update(n => n + 1), reset: () => set(0) };
}
export const counter = createCounter();Struktur alur
Loading diagram...
Catatan implementasi
$storehanya berlaku di dalam.svelte; di.jspakaisubscribemanual.writablepunya.set,.update,.subscribe.derivedbisa menggabungkan banyak store:derived([a, b], ([$a, $b]) => ...).- Custom store cukup mengembalikan
{ subscribe, ...method }(contract minimal).
Kesalahan umum
- Subscrib manual lupa unsubscribe: memory leak; di
.sveltepakai$agar otomatis. - Mutasi isi store tanpa set/update:
arr.push()tidak notify; pakaiupdate. - Over-global: tidak semua state butuh store; state lokal lebih sederhana.
- Derived dependency tidak list: pastikan array store benar di argumen pertama.