0
0
Svelteframework~30 mins

Why stores manage shared state in Svelte - See It in Action

Choose your learning style9 modes available
Why stores manage shared state
📖 Scenario: You are building a simple Svelte app where two components need to share and update the same number value. Without a shared store, keeping these components in sync is hard.
🎯 Goal: Create a Svelte store to hold a shared number value. Then use this store in two components so that when one updates the number, the other automatically shows the updated value.
📋 What You'll Learn
Create a writable store called count with initial value 0
Create a variable incrementAmount set to 1
Use the count store in a component to display the current count
Add a button that increases count by incrementAmount when clicked
💡 Why This Matters
🌍 Real World
Many apps need multiple parts to share and update the same data, like user info or settings. Stores make this easy and keep UI in sync.
💼 Career
Understanding stores is key for building reactive apps with Svelte, a popular modern framework used in web development jobs.
Progress0 / 4 steps
1
Create the shared store
Create a writable store called count with initial value 0 by importing writable from 'svelte/store'.
Svelte
Hint

Use import { writable } from 'svelte/store' and then export const count = writable(0).

2
Add a configuration variable
Create a variable called incrementAmount and set it to 1 inside your Svelte component script.
Svelte
Hint

Just write let incrementAmount = 1 inside the script.

3
Use the store and update logic
In your Svelte component, subscribe to the count store using $count and add a button with an on:click event that updates count by adding incrementAmount.
Svelte
Hint

Define a function increment that calls count.update(n => n + incrementAmount).

4
Complete the component with display and button
Add HTML to display the current value of $count and a button with on:click={increment} that increases the count.
Svelte
Hint

Use {$count} to show the count and a button with on:click={increment}.