
How to Manage State Across Different Components in Svelte
You can use a writable
store in Svelte to manage state across different components. A store is an object that is enhanced with methods that you can use to read, write, and listen to changes in it:
<script>
import { writable } from 'svelte/store';
const stores = writable([]);
// logs out []
stores.subscribe(value => console.log(value));
// logs out: [βπͺβ]
stores.set(['πͺ']);
// logs out: [βπͺβ, βπ¬β]
stores.update(stores => [...stores, 'π¬']);
</script>
Copied to clipboard!
Writable stores have the following methods:
subscribe:
Subscribes to the store and listen for changes. The callback is called with the value whenever the store is changed.set:
Sets the store to a given value.update:
Updates the store using a callback function.


Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.

Resources:
Tired of looking for tutorials?
You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.
Check out our interactive course to master JavaScript in less time.
Learn More