Context API
Utilities for sharing instances across components using React Context.
createGenericContext
Creates a React context, mainly designed for sharing instances (stable references).
Signature
function createGenericContext<T>(): {
Provider: React.ComponentType<{ value: T; children: React.ReactNode }>;
useContext: () => T;
};
Example
import { useRef } from 'react';
const [CounterProvider, useCounter] = createGenericContext<CounterManager>();
function App() {
const manager = useDisposable(() => new CounterManager());
return (
<CounterProvider value={manager}>
<Child />
</CounterProvider>
);
}
function Child() {
const manager = useCounter();
const { count } = useReactiveValues({ count: manager.count });
return <div>{count}</div>;
}
createHydrationContext
Creates a context for SSR with hydration.
Signature
function createHydrationContext<T>(
serialize: (value: T) => unknown,
deserialize: (value: unknown) => T,
): {
Provider: React.ComponentType<{ value: T; children: React.ReactNode }>;
useContext: () => T;
};
This is useful for Next.js and other SSR frameworks where you need to serialize state on the server and hydrate it on the client.
Example
import { createHydrationContext } from '@dxbox/use-less-react/client';
const [StoreProvider, useStore] = createHydrationContext(
(store) => store.toPlainObject(), // serialize
(data) => ReactiveStore.fromPlainObject(data), // deserialize
);
// Server-side
function ServerComponent() {
const store = new ReactiveStore({...});
return (
<StoreProvider value={store}>
<ClientComponent />
</StoreProvider>
);
}
// Client-side
function ClientComponent() {
const store = useStore(); // Hydrated from server
// ...
}