Stores
นักพัฒนา React มักใช้ Context + useReducer, Redux หรือ Zustand เพื่อจัดการ shared state ข้ามคอมโพเนนต์ Svelte มี stores ในตัว: writable (อ่านและเขียนได้), readable (อ่านได้อย่างเดียว), และ derived (คำนวณค่าจาก stores อื่น) ใน markup ให้ใส่เครื่องหมาย $ นำหน้าชื่อ store เพื่อ auto-subscribe — Svelte จะ subscribe และ unsubscribe ให้อัตโนมัติ
writable store เทียบกับ Zustand
หัวข้อที่มีชื่อว่า “writable store เทียบกับ Zustand”// store.js (Zustand)import { create } from 'zustand';
export const useCountStore = create(set => ({ count: 0, increment: () => set(s => ({ count: s.count + 1 })), reset: () => set({ count: 0 }),}));
// Component.jsxfunction Counter() { const { count, increment } = useCountStore(); return <button onClick={increment}>Count: {count}</button>;}<!-- store.js -->import { writable } from 'svelte/store';export const count = writable(0);
<!-- Counter.svelte --><script> import { count } from './store.js';</script>
<button onclick={() => count.update(n => n + 1)}> Count: {$count}</button>derived store เทียบกับ useSelector
หัวข้อที่มีชื่อว่า “derived store เทียบกับ useSelector”// Zustand selectorconst double = useCountStore(s => s.count * 2);<script> import { derived } from 'svelte/store'; import { count } from './store.js';
const doubleCount = derived(count, $count => $count * 2);</script>
<p>Double: {$doubleCount}</p>