Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 39 ยท Stores and Context

The Context API

Share signals and stores across a component tree with SolidJS context. Learn createContext, Provider, useContext, safe custom hooks, nested providers and typical patterns.

Props are the normal way to pass data down, but passing a value through five layers of components that do not use it (called prop drilling) is tedious. Context lets a component near the top of the tree publish a value, and any descendant read it directly, no matter how deep.

In Solid, context is especially pleasant because the value you share is usually a signal or a store. The context itself never changes; the reactive thing inside it does. That means components that read it update precisely, without re-rendering anything.

The three pieces

  1. createContext(defaultValue?) creates a context object.
  2. Context.Provider wraps part of the tree and supplies a value.
  3. useContext(Context) reads the nearest provider's value.
JSX
import { createContext, useContext, createSignal } from "solid-js";

const ThemeContext = createContext("light"); // default used with no provider

function ThemeProvider(props) {
  const [theme, setTheme] = createSignal("light");
  const value = { theme, toggle: () => setTheme((t) => (t === "light" ? "dark" : "light")) };
  return (
    <ThemeContext.Provider value={value}>
      {props.children}
    </ThemeContext.Provider>
  );
}

function ThemeButton() {
  const ctx = useContext(ThemeContext);
  return <button onClick={ctx.toggle}>Theme: {ctx.theme()}</button>;
}

Notice that the shared value is a plain object holding an accessor (theme) and an action (toggle). The object is created once; only the signal inside changes.

flowchart TD
  P["ThemeProvider<br/>owns the signal"] --> A["Layout"]
  A --> B["Sidebar"]
  A --> C["Content"]
  C --> D["ThemeButton<br/>useContext"]
  B --> E["Logo<br/>useContext"]
  P -. "value" .-> D
  P -. "value" .-> E

Components in between do not need to know that the context exists.

A theme context

Panel, Label and ToggleButton never receive a prop, yet they all share one theme. Click the button: only the two reactive spots (the label text and the panel style) update.

The default value and the missing provider

createContext(default) supplies default when there is no provider above. If you call createContext() with no argument, useContext returns undefined outside a provider, and the first property access crashes with a confusing message. A good habit is to wrap useContext in a custom hook that fails loudly:

JSX
const CartContext = createContext();

export function useCart() {
  const ctx = useContext(CartContext);
  if (!ctx) {
    throw new Error("useCart must be used inside <CartProvider>");
  }
  return ctx;
}

Components then call useCart() and never import CartContext directly. This also lets you change the shape of the context later in one place.

Context with a store and actions

Because stores are reactive objects, they pair naturally with context. The provider creates the store and exposes read access plus named actions. Consumers can read state but change it only through the actions, which keeps data flow one-way.

A counter store through context

This [state, actions] tuple is a very common convention. It mirrors createStore itself and reads naturally: const [cart, { addItem }] = useCart().

Nested providers and overriding

useContext finds the nearest provider above the component. Nesting a second provider of the same context overrides the value for its subtree, which is handy for section-specific themes, per-row form state or testing with fake services:

JSX
<ThemeContext.Provider value={lightTheme}>
  <Page />
  <ThemeContext.Provider value={darkTheme}>
    <Footer />  {/* sees darkTheme */}
  </ThemeContext.Provider>
</ThemeContext.Provider>

Context rules and pitfalls

  • Call useContext while the component is running, not later inside a timeout or event handler. Read it at the top of your component and use the result afterward.
  • Share reactive things. If the context value is a plain object that you replace, consumers will not notice. Put signals or stores inside it.
  • Do not overuse it. Local state and props are simpler. Reach for context for genuinely shared concerns: theme, current user, router, shopping cart, i18n.
  • Unlike some frameworks, changing a context value does not re-render consumers; there is no re-rendering. Only the reactive reads update.

Next, see how bigger apps organize this into modules in Global State Patterns.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What are the three main pieces of the context API?

    You create a context, wrap the tree in its Provider and read it with useContext.
  2. 2. Why share a signal or store inside the context value instead of a plain changing value?

    The context object itself is created once. Reactivity comes from the signal or store inside it.
  3. 3. What does useContext return when there is no provider and no default value?

    It returns undefined, which is why a custom hook that checks for it and throws a clear error is a good habit.
  4. 4. Which provider does useContext read when two providers of the same context are nested?

    The closest ancestor provider wins, so inner providers override outer ones for their subtree.

Summary

  • Context shares values with a whole subtree without prop drilling.
  • Put signals or stores (and actions) in the value so consumers stay reactive.
  • Wrap useContext in a custom hook that throws if the provider is missing.
  • The nearest provider wins; call useContext during component setup.

Next: Global State Patterns