Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Leer Understanding Stores | Stores and Shared State
Introduction to Svelte

Understanding Stores

Veeg om het menu te tonen

As applications grow larger, multiple components often need access to the same data. Passing props through many layers of components can quickly become difficult to manage.

Svelte solves this problem using stores.

What Are Stores?

Stores are special objects used to share reactive data across different components.

Instead of keeping all state inside a single component, stores allow multiple parts of the application to access and update the same data.

This makes state management much easier in larger applications.

Why Shared State Matters

Imagine a shopping cart in an online store. Multiple components may need access to the cart data at the same time:

  • A product card may add items;
  • A cart icon may display the item count;
  • A checkout page may show the full cart contents.

Without shared state management, passing data between many components becomes difficult and repetitive.

Stores help centralize this data.

Creating Your First Store

Create a new folder called stores inside the src directory.

Then create a file called counterStore.js:

import { writable } from 'svelte/store';

export const count = writable(0);

The writable() function creates a reactive store with an initial value.

Using the Store

Open App.svelte and import the store:

<script>
  import { count } from './stores/counterStore.js';
</script>

<h2>Count: {$count}</h2>

<button on:click={() => $count += 1}>
  Increase
</button>

The $count syntax automatically subscribes to the store and keeps the interface updated when the value changes.

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 4. Hoofdstuk 1

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

Sectie 4. Hoofdstuk 1
some-alt