API reference · generated from source
Function: createRetreeContext()#
function createRetreeContext<T>(name?): RetreeContext<T>;Defined in: context.ts:120
Create a typed Provider + useRootContext pair for a per-tree container
of Retree roots.
Type Parameters#
| Type Parameter |
|---|
T |
Parameters#
| Parameter | Type | Default value | Description |
|---|---|---|---|
name | string | "RetreeProvider" | Optional display name used in React DevTools and in the missing-provider error message. Defaults to "RetreeProvider". |
Returns#
A RetreeContext with Provider and useRootContext
bound to T.
Remarks#
Module-singleton roots (const app = Retree.root(...) at module scope) are
shared by everything that imports the module. That is often what you want
in a client-only app — but in SSR frameworks (Next.js, Remix) module state
is shared across requests on the server, so one user's writes leak into
another user's render. It also makes tests share state unless every test
carefully resets the module. Provider-created roots solve both: the
create factory runs once per mounted provider, so each server request
(and each test render) gets its own container of roots.
Prefer this factory over the default RetreeProvider /
useRootContext pair when you want the container type to flow
without a type argument at every call site: the T you create the context
with is the T every useRootContext() returns.
The returned Provider is a client component ("use client"), so it can
be rendered from a server component but its create factory runs in the
client/SSR render pass, not in React Server Components.
Example#
import { Retree } from "@retreejs/core";
import { createRetreeContext } from "@retreejs/react";
class AppState {
count = 0;
}
function createRoots() {
return { app: Retree.root(new AppState()) };
}
const { Provider: AppProvider, useRootContext: useAppRoots } =
createRetreeContext<ReturnType<typeof createRoots>>("AppProvider");
function Counter() {
const { app } = useAppRoots(); // typed — no cast, no type argument
const state = useNode(app);
return <button onClick={() => (state.count += 1)}>{state.count}</button>;
}
export function App() {
return (
<AppProvider create={createRoots}>
<Counter />
</AppProvider>
);
}