Askr
Fundamentals

Scopes

Use scopes with the current published Askr packages.

  • @askrjs/askr0.0.59

How to use scopes

Define a typed scope once, provide it at the ownership boundary, and read it only from descendants that require the service.

  1. Import the published @askrjs/askr entrypoint.
  2. Keep scopes configuration next to the component, route, or server composition root that owns it.
  3. Handle pending, unavailable, cancellation, and failure states, then verify the production path.
import { defineScope, readScope } from '@askrjs/askr';

const ProjectsScope = defineScope<ProjectsService>(defaultProjects);

<ProjectsScope value={projects}>
  <ProjectRoutes />
</ProjectsScope>

const projects = readScope(ProjectsScope);

Define a scope

`defineScope(defaultValue)` creates a `Scope<T>` — a callable component-like object carrying a unique key and a default value, used to pass data down through the tree without threading it through every layer of props. It's Askr's equivalent of React context, but built on the same function-based vocabulary as everything else in the library rather than a class-based Provider.

Provide values

Render the scope itself as a component to provide a value to its subtree: `<MyScope value={theme}>{children}</MyScope>`. Everything under that element sees `value` when it calls `readScope(MyScope)`, and nesting another `<MyScope value={...}>` further down overrides it for just that inner subtree.

Read values

`readScope(scope)` returns the nearest provided value for that scope, or its `defaultValue` if nothing above provided one. Like `state()`, it reads from the current component's context frame, so it needs to be called during render rather than stashed and reused later.

Ownership and cleanup

Scope values live on a `ContextFrame` that's attached to the component tree and torn down along with it — there's no manual unsubscribe step. Because a scope's value is looked up by walking frames at read time rather than copied into local state, updating the value provided at the top of the tree is visible immediately to every reader below it, without needing an separate notification mechanism.