Context system for dependency injection and sharing state across component boundaries. Qwik's context system enables efficient data sharing without prop drilling.
Create and consume context values across component boundaries.
/**
* Create context identifier
* @param name - Context name for debugging
* @returns Context identifier
*/
function createContextId<T>(name: string): ContextId<T>;
/**
* Provide context value to child components
* @param id - Context identifier
* @param value - Value to provide
*/
function useContextProvider<T>(id: ContextId<T>, value: T): void;
/**
* Access context value from parent providers
* @param id - Context identifier
* @returns Context value
*/
function useContext<T>(id: ContextId<T>): T;
// Context identifier interface
interface ContextId<T> {
readonly __context__: T;
}Usage Examples:
import {
component$,
createContextId,
useContextProvider,
useContext,
useStore
} from "@builder.io/qwik";
// Create context for theme
interface Theme {
mode: "light" | "dark";
primaryColor: string;
}
const ThemeContext = createContextId<Theme>("theme");
// Root provider component
export const App = component$(() => {
const theme = useStore<Theme>({
mode: "light",
primaryColor: "#007acc",
});
// Provide theme to all children
useContextProvider(ThemeContext, theme);
return (
<div>
<Header />
<Main />
<Footer />
</div>
);
});
// Consumer component
export const Header = component$(() => {
const theme = useContext(ThemeContext);
return (
<header
style={{
backgroundColor: theme.mode === "dark" ? "#1a1a1a" : "#ffffff",
color: theme.primaryColor,
}}
>
<h1>My App</h1>
<ThemeToggle />
</header>
);
});
// Another consumer component
export const ThemeToggle = component$(() => {
const theme = useContext(ThemeContext);
return (
<button
onClick$={() => {
theme.mode = theme.mode === "light" ? "dark" : "light";
}}
>
Toggle to {theme.mode === "light" ? "dark" : "light"} mode
</button>
);
});