Nadia's Bookshop's currency and theme are read in many places: the header, every book card, the cart. Sent through props, the value has to be passed down level by level, including through components in the middle that don't need it at all. If you come from React, you know this problem as prop drilling, and the fix is the same: context.
Context shares one value with every component under a Provider. createContext(defaultValue) makes the container, <X.Provider value={...}> provides the value to everything inside it, and useContext(X) reads it from the nearest Provider above. Say Nadia's Bookshop opens a branch in London. The price labels on the shelves aren't told the currency one by one. Each label reads the sign on the wall of the shop it hangs in: in the home shop it says $, in the London branch it says £. A label printed in a flyer, outside any shop, uses the currency printed on the label itself, its default value.
createContext, Provider, useContext
import { createContext, useContext } from "solid-js"
const ThemeContext = createContext("light")
function ThemedText() {
const theme = useContext(ThemeContext)
return <p>Theme: {theme}</p>
}
function App() {
return (
<ThemeContext.Provider value="dark">
<ThemedText />
</ThemeContext.Provider>
)
}
The result is Theme: dark.
createContext("light")makes a context with the default value"light". It's made once, outside any component, so the provider and the reader use the same context.<ThemeContext.Provider value="dark">provides"dark"to every component inside it, however deep.useContext(ThemeContext)inThemedTextlooks for the nearest Provider above it and returns itsvalue.ThemedTextreceives no prop at all. This is the first exercise.
Outside the Provider: the default value
Nadia's Bookshop with the currency and the theme in a context:
import { createContext, createSignal, useContext } from "solid-js"
const ShopContext = createContext({ currency: "$", theme: () => "light" })
function Header() {
const shop = useContext(ShopContext)
return <header class={shop.theme()}>Nadia's Bookshop · prices in {shop.currency}</header>
}
function BookCard(props) {
const shop = useContext(ShopContext)
return (
<div class={"card " + shop.theme()}>
<h3>{props.title}</h3>
<p>{shop.currency}{props.price}</p>
</div>
)
}
function App() {
const [theme, setTheme] = createSignal("light")
const toggle = () => setTheme(t => (t === "light" ? "dark" : "light"))
return (
<div>
<Header />
<ShopContext.Provider value={{ currency: "$", theme }}>
<button onClick={toggle}>Toggle theme</button>
<BookCard title="The Rainbow Troops" price={18} />
<BookCard title="This Earth of Mankind" price={24} />
<ShopContext.Provider value={{ currency: "£", theme }}>
<BookCard title="The Rainbow Troops (London branch)" price={14} />
</ShopContext.Provider>
</ShopContext.Provider>
</div>
)
}
Tested in Solid 1.9, after Toggle theme is clicked:
| Component | useContext gets it from |
Shows |
|---|---|---|
Header |
no Provider above it: the default value | prices in $, class light |
| The Rainbow Troops, This Earth of Mankind cards | the outer Provider | $18, $24, class card dark |
| The London branch card | the inner Provider, the nearest | £14, class card dark |
Header stays light. It isn't inside any Provider, so useContext returns the default value from createContext, whose theme is always "light". A context only reaches the components inside its Provider. If the context is made with no default, createContext(), a component outside the Provider gets undefined, and shop.currency stops with TypeError: Cannot read properties of undefined (reading 'currency'). The London branch card sits inside two Providers, and the nearest one wins: £14.
A value that can change
A Provider reads value once, when it's made. For its readers to follow changes, send the signal, not the result of reading it:
value |
Its readers write | When the theme changes |
|---|---|---|
{{ currency: "$", theme }} |
shop.theme() |
the cards turn dark |
{{ currency: "$", theme: theme() }} |
shop.theme |
stays light, because only the string "light" was sent |
The second exercise uses the same pattern for a user name:
import { createContext, useContext, createSignal } from "solid-js"
const UserContext = createContext()
function UserDisplay() {
const ctx = useContext(UserContext)
return <p>User: {ctx.name()}</p>
}
function App() {
const [name, setName] = createSignal("Andi")
return (
<UserContext.Provider value={{ name, setName }}>
<UserDisplay />
</UserContext.Provider>
)
}
value={{ name, setName }}sends the signal and its setter. The first curly brace belongs to JSX, the second is the object.ctx.name()is read with parentheses, so the paragraph follows along if something callsctx.setName("Budi"). The result isUser: Andi.- The name in the paragraph is read from the context, not typed as
User: Andidirectly. The exercise checks for a{after<p>.
In a real app, the Provider is usually wrapped in its own component that holds the data, plus one function to read it:
import { createContext, createSignal, useContext } from "solid-js"
const CartContext = createContext()
export function CartProvider(props) {
const [items, setItems] = createSignal([])
const cart = {
items,
add: (book) => setItems((c) => [...c, book]),
total: () => items().reduce((t, b) => t + b.price, 0),
}
return <CartContext.Provider value={cart}>{props.children}</CartContext.Provider>
}
export function useCart() {
const cart = useContext(CartContext)
if (!cart) throw new Error("useCart must be used inside <CartProvider>")
return cart
}
- Any component inside
<CartProvider>only writesconst cart = useCart(), thencart.add(book)orcart.total(). Tested on Solid 1.9: after adding a book priced 18 twice,cart.total()is36. - The cart can only be changed through
add, becausesetItemsis not shared. - Outside the Provider,
useCart()stops right away with a clear message, not aTypeErrorsomewhere else.
When to use context
For a value many components read at different depths: the theme, the currency, the language, the signed-in user. If only one child needs it, props are clearer. One more thing: useContext is called while the component runs. Called later, say inside a setTimeout, it no longer knows its place in the component tree and returns the default value.
⚠️ Why you get the default value, or a stale one
- A component outside the Provider. It gets the default value, or
undefinedifcreateContext()was made without one. Make sure the component is inside<X.Provider>. value={theme()}. The Provider reads it once, so its readers are stuck on the first value. Send the signal:value={{ theme }}, then readshop.theme().- The value typed in directly.
<p>User: Andi</p>shows the right thing, but doesn't read the context. The second exercise checks that the paragraph joins in a value with{...}. useContextcalled later. Inside asetTimeoutor after anawait,useContext(ShopContext)returns the default value, even though the component sits inside the Provider. Call it in the component body, keep the result in a variable, then use that variable.
TL;DR: const ThemeContext = createContext("light") is made once, outside components. <ThemeContext.Provider value="dark"> provides a value to everything inside it, and useContext(ThemeContext) reads it from the nearest Provider above: Theme: dark. Outside a Provider, useContext returns the default value from createContext (or undefined if there is none). Nested Providers: the nearest wins. A Provider reads value once, so send the signal (value={{ name, setName }}) and read it with parentheses (ctx.name()) so the view follows changes.
⚡ createContext, Provider, useContext
Write:
const ThemeContext = createContext("light")
function ThemedText() {
const theme = useContext(ThemeContext)
return <p>Theme: {theme}</p>
}
<ThemeContext.Provider value="dark">
<ThemedText />
</ThemeContext.Provider>
Meaning: A context is made once, outside any component. The Provider provides its value to every component inside it, however deep, and useContext reads it from the nearest Provider above. The result is Theme: dark, with no prop at all.
⚡ Outside the Provider: the default value
Guess first: Header calls useContext(ShopContext) but isn't inside any Provider. The theme is switched to dark. Does Header turn dark too?
No, it stays light. Outside a Provider, useContext returns the default value from createContext, whose theme is always "light".
Meaning: A context only reaches the components inside its Provider. With no default, createContext(), the result is undefined. Nested Providers: the nearest wins.
⚡ Send the signal, not the result of reading it
Write:
<UserContext.Provider value={{ name, setName }}>
<UserDisplay />
</UserContext.Provider>
Meaning: A Provider reads value once, when it's made. Send the signal, then read it with parentheses, ctx.name(), so the view follows changes.