Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 39 ยท Stores and Context

Global State Patterns

Compare the three ways to share state in SolidJS: module-level signals, module-level stores and context providers, and learn when each one is the right choice.

Sooner or later two distant components need the same data: the logged-in user, a theme, a shopping cart. In React you would reach for a context or a state library. In Solid you have a simpler first option, because signals and stores are not tied to components. They are plain reactive primitives that you can create anywhere.

This lesson walks through the three patterns for global state, shows what each one is good at, and ends with a rule of thumb for choosing. You already know signals, stores and the context API; here you combine them.

Pattern 1: a module-level signal

A signal created at the top level of a module is shared by every file that imports it. There is no provider and no hook.

JavaScript
// theme.js
import { createSignal } from "solid-js";

export const [theme, setTheme] = createSignal("light");
export const toggleTheme = () => setTheme((t) => (t === "light" ? "dark" : "light"));

Any component can import { theme, toggleTheme } from "./theme" and read theme() in JSX. When the value changes, only the places that read it update.

One signal shared by two widgets

The two components never talk to each other. They only share the signal, and the DOM updates are exact.

Module-level state is shared by everyone who runs that module. In a browser that is exactly what you want. With server-side rendering (for example SolidStart) one server process handles many visitors, so a module-level signal holding per-user data would leak between requests. Use context for per-request or per-user state on the server.

Pattern 2: a module-level store

If the shared data is structured, do the same with createStore, and export the store together with named actions instead of exporting the raw setter. Callers then cannot put the data in an invalid state.

JavaScript
// cart.js
import { createStore } from "solid-js/store";

const [cart, setCart] = createStore({ items: [] });

export const addItem = (product) => {
  const existing = cart.items.find((i) => i.id === product.id);
  if (existing) {
    setCart("items", (i) => i.id === product.id, "qty", (q) => q + 1);
  } else {
    setCart("items", cart.items.length, { ...product, qty: 1 });
  }
};
export const removeItem = (id) =>
  setCart("items", (items) => items.filter((i) => i.id !== id));

export const total = () => cart.items.reduce((sum, i) => sum + i.price * i.qty, 0);
export { cart };

Notice three habits. The setter stays private. Mutations are named functions. And total is a derived function that reads the store, so any JSX that calls total() stays up to date.

A shared cart with actions

Pattern 3: context with a provider

Context is the right tool when the state must be created per subtree: one instance per page, per test, per user on the server, or when different parts of the tree need different instances of the same logic. The usual shape is a provider component that creates the state and a custom hook that reads it:

JSX
import { createContext, useContext } from "solid-js";
import { createStore } from "solid-js/store";

const CounterContext = createContext();

export function CounterProvider(props) {
  const [state, setState] = createStore({ count: props.start ?? 0 });
  const value = {
    state,
    increment: () => setState("count", (c) => c + 1),
  };
  return (
    <CounterContext.Provider value={value}>
      {props.children}
    </CounterContext.Provider>
  );
}

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

Because the store lives inside the provider function, every <CounterProvider> makes its own independent counter. That is impossible with a module-level store, which is a singleton.

flowchart TD
  A["Module state: one instance per app"] --> B["Simple, no provider"]
  C["Context state: one instance per Provider"] --> D["Per-subtree, per-request, easy to test"]

Module state is a singleton. Context state is created every time its provider is rendered.

Choosing between the patterns

Need Pick
A single value used app-wide (theme, sidebar open) Module-level signal
A structured collection used app-wide (cart, notifications) Module-level store with actions
State that must differ per subtree, per test or per server request Context provider
Data that comes from a server A resource, not hand-written state

A good default is to start with a module-level signal or store, which is the least code, and move to context when you hit one of the reasons in the table. Moving later is easy because consumers already use functions (useCart() instead of importing cart directly) if you wrapped access in a small function from the start.

Avoiding common mistakes

  • Exporting the setter. Anyone can then write anything. Export actions.
  • Destructuring a store. const { items } = cart reads the value once and loses reactivity. Read cart.items where you use it.
  • Creating a signal inside a component and expecting sharing. A signal created in a component body is created again for every instance of that component.
  • Putting server data in global state by hand. Fetching, caching and revalidating are what resources and route queries are for.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where must a signal be created so that many components share it without a provider?

    A signal declared at the top of a module exists once, and every importer shares it.
  2. 2. Why export named action functions instead of the store setter?

    Named actions keep all changes in one place and enforce the rules of the data.
  3. 3. When is context preferable to a module-level store?

    A provider creates fresh state each time it renders, which a singleton module cannot do.
  4. 4. What happens with const { items } = cart in a component body?

    Destructuring reads the property immediately, outside a tracking scope, so later changes are not seen.

Summary

  • Signals and stores are not bound to components, so a module can own global state.
  • Export reads and named actions; keep the setter private.
  • Use context when state must be created per subtree, per test or per server request.
  • Do not hold server data in hand-written global state when a resource fits.

Next: Persisting State and Undo History