πŸŽ‰ We just launched our new React course! Get it with 20% off! πŸŽ‰
How to Manage State Across Different Components in Svelte

How to Manage State Across Different Components in Svelte

Ferenc Almasi β€’ πŸ”„ 2020 October 18 β€’ πŸ“– 1 min read
  • twitter
  • facebook

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>
Stores.svelte
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.
How to Manage State Across Different Components in Svelte
If you would like to see more Webtips, follow @flowforfrank

Looking into SvelteΒ 3
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript

Resources:

JavaScript Course Dashboard

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

Recommended