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';
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';
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.
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.
Also, stores are shared across all users if SSR is enabled, which may be a security issue.
Context is used to share data across decendent child components, while Store is used to share data across the whole application.
© 2022 - 2024 — McMap. All rights reserved.