Skip to content

useResolve

useResolve reads one instance out of the nearest module. It resolves once and hands back the same instance on every later render. Where the instance comes from is Providers & Resolution; this page is the API surface.

Signature

ts
useResolve<T>(token: InjectionToken<T>, mode: ResolveMode = "nearest"): T

The token is a class or a symbol minted by makeTokenizer, and the return type comes from the token. There is no type argument to pass and no cast to write.

tsx
import { useSyncExternalStore } from "react"
import { useResolve } from "@remodulo/react"

function OrderList() {
    // A read: the same instance on every render, and it never re-renders on its own. The
    // subscription below is what puts orders on screen.
    const store = useResolve(OrdersStore)
    const orders = useSyncExternalStore(store.subscribe, store.getSnapshot)

    return <ul>{orders.map((order) => <li key={order.id}>{order.title}</li>)}</ul>
}

OrderList resolves OrdersStore once and subscribes to it separately - the hook produced the instance, not the render.

It is a read, not a subscription

useResolve never re-renders your component. An instance whose fields change is still the same instance, and React has no way to know anything happened. What puts a change on screen is your state layer: Connecting Reactivity.

Modes

ModeLooks at
"nearest" (default)This module, then up the chain, stopping at the first module that has the binding.
"self"This module's own registrations only. An inherited registration is a miss.

The snapshot

The hook keeps one snapshot of (resolver, token, mode) and the value it produced. It resolves again only when one of the three changes identity - a reference comparison, never a deep one. Same resolver, same token, same mode means the container is never touched again.

A rebuild replaces the module, so the resolver is a different object and the read happens again against the new one.

When it throws

When the token is registered nowhere the mode can see, and when the module is not in a state to answer - created, failed or destroyed, here or on any ancestor. Lifecycle has the second kind and Errors has the exact messages.

Where to go next

Guides

Reference

MIT licensed.