Context
A wrapper around Svelte's Context API that provides type safety and improved ergonomics for sharing data between components.
Context allows you to pass data through the component tree without explicitly passing props through every level. It's useful for sharing data that many components need, like themes, authentication state, or localization preferences.
The Context
class provides a type-safe way to define, set, and retrieve context values.
Usage
Creating a Context
First, create a Context
instance with the type of value it will hold:
Creating a Context
instance only defines the context - it doesn't actually set any value. The
value passed to the constructor ("theme"
in this example) is just an identifier used for debugging
and error messages.
Think of this step as creating a "container" that will later hold your context value. The container
is typed (in this case to only accept "light"
or "dark"
as values) but remains empty until you
explicitly call myTheme.set()
during component initialization.
This separation between defining and setting context allows you to:
- Keep context definitions in separate files
- Reuse the same context definition across different parts of your app
- Maintain type safety throughout your application
- Set different values for the same context in different component trees
Setting Context Values
Set the context value in a parent component during initialization.
Note
Context must be set during component initialization, similar to lifecycle functions like onMount
.
You cannot set context inside event handlers or callbacks.
Reading Context Values
Child components can access the context using get()
or getOr()