Context
Use context() to create a reactive value that can be shared across multiple
components without passing it through inputs. Any component that reads
a context value will react to its changes automatically.
The first argument is a unique key, the second is the initial value. Read the
current value by calling it as a function — pokemon() — and update it by
passing a new value — pokemon("bulbasaur"). Both work anywhere in your
component tree.
Context is the right tool when the same piece of state needs to be consumed by
components that don't share a direct parent-child relationship, or when threading
it through .input() would create unnecessary coupling. In the
example above, PokemonPicker writes to the context via .bind(), and
PokemonCard reads it in .derived() — the two components stay fully decoupled.
Because context values are reactive, any .derived() or .effect() that reads
a context value will re-run when it changes — just like state. Here, changing the
selected Pokémon automatically re-triggers the pokemonData fetch and re-renders
the stats and sprite without any additional wiring.
Pokémon and PokéDex are trademarks of Nintendo/Creatures Inc./GAME FREAK inc. This tutorial uses the PokéAPI for educational purposes only and is not affiliated with or endorsed by the Pokémon Company.
Similar concepts
- React:
createContext/useContext - Vue:
provide/inject - Svelte:
setContext/getContext