sveltestore

difference between svelte store and svelte context


What is exact different between Svelte Context and Svelte Store?
When to use in different situation?

import { getContext } from 'svelte';
import { writable } from 'svelte/store';

Solution

  • A context is data that is inherited within a component hierarchy.
    Stores encapsulate reactivity via a subscription system.

    Contexts are useful for making data available to large parts of an application (e.g. localization data or current user info) without having to pass it through props at every level. This allows components that do not "know" about the context to exist in-between without interference, e.g. third party components.

    Stores allow reactivity to pass component boundaries in Svelte 3 & 4. E.g. changes to variables in regular JS/TS files are not captured by Svelte. By passing a store around, a component can subscribe to the changes (via $ syntax) and automatically update.

    In Svelte 5, state reactivity works across function boundaries and can be declared outside of components in .svelte.js/.svelte.ts files, so stores are essentially obsolete there.

    Contexts are not reactive by default, so it often makes sense to pass stores/state through contexts.


    There is a common misconception that stores are associated with being global. This has nothing to do with stores; any object directly exported from a module behaves that way.

    You can of course use stores that way, but it comes with all the upsides and downsides of a singleton. E.g. it is easy to access but makes testing messier and potentially unparallelizable because multiple tests would try to change and read the value at the same time.

    Global state is also a huge security and privacy concern when using server-side rendering. There is only one instance of said state on the server that is shared between all requests.

    Personally, I would recommend injecting stores meant to be accessed anywhere in the application as a context at the root of the component tree.