What is Svelte's context API?
Answer
Svelte's context API provides a way to pass data deep into the component tree without prop drilling, but unlike stores, context is scoped to a component subtree (not global). setContext: sets a value in the current component's context, available to all descendants: import { setContext } from 'svelte'; setContext('user', currentUser);. getContext: retrieves a value from the nearest ancestor that set it: import { getContext } from 'svelte'; const user = getContext('user');. Context is not reactive by default — if you need reactive context, store a writable store in context. Use cases: theme providers, user context for deeply nested components, component library configuration. Difference from stores: stores are application-global; context is component-tree-scoped (multiple instances of a component each get their own context). Context values are only accessible during component initialization.
Previous
How does SvelteKit handle API routes?
Next
What is the difference between client-side navigation and page reloads in SvelteKit?
More Svelte / SvelteKit Questions
View all →- Intermediate What are Svelte custom stores and the store contract?
- Intermediate How does SSR (Server-Side Rendering) work in SvelteKit?
- Intermediate What are SvelteKit adapters?
- Intermediate What is the difference between prerendering, SSR, and CSR in SvelteKit?
- Intermediate How do you manage environment variables in SvelteKit?