difference between svelte store and svelte context
Asked Answered
C

4

12

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';
Coulter answered 8/11, 2022 at 13:55 Comment(0)
C
21

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. 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.

Contexts are also not reactive by default, so it often makes sense to pass stores through contexts as well.


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.

Calabrese answered 8/11, 2022 at 14:27 Comment(0)
H
1

the way i see it, the context is like props with steroids, meaning an ancestor can share data to any deep nested component. i think this feature was also part of the react.

The store, on the other hand is a context with god like omnipotence. it can be used to share data at any level of the component tree.

Harbour answered 20/2, 2023 at 21:8 Comment(0)
S
0

Also, stores are shared across all users if SSR is enabled, which may be a security issue.

Sitar answered 15/3, 2023 at 9:3 Comment(1)
Store and context are meant for client side code. If you want to store data on server side, use node-cache, redis or some other server side storeInsulator
I
0

Context is used to share data across decendent child components, while Store is used to share data across the whole application.

Insulator answered 28/4 at 15:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.