smolter
API

useOutletContext

Read a typed value supplied by an ancestor Outlet.

Compatibility

ReactAvailable in this renderer's browser integration.
React SSRAvailable to this renderer's SSR integration; browser event handlers run after hydration.
PreactAvailable in this renderer's browser integration.
Preact SSRAvailable to this renderer's SSR integration; browser event handlers run after hydration.

Import from @kasperrt/smolter/react @kasperrt/smolter/preact

Signature

function useOutletContext<T>(): T;

Parameters

Takes no runtime arguments. Specify the context shape as its type argument; TypeScript cannot infer a provider’s type across the component tree.

Returns

Returns the nearest Outlet context cast to T. There is no runtime validation. Without a provider the value is undefined, so include undefined in T when a missing provider is an expected state.

Example

Define the context contract once and import it in the layout and its children.

import { Outlet, useOutletContext } from "@kasperrt/smolter/preact";

interface PageContext {
  canEdit: boolean;
}

export function Layout() {
  return <Outlet context={{ canEdit: true }} />;
}

export function EditStatus() {
  const context = useOutletContext<PageContext>();

  return <span>{context.canEdit ? "Editable" : "Read only"}</span>;
}

Inheritance

Outlet inherits its ancestor context when its context prop is null or undefined. This is component context, not a second loader store. Keep server data in loaders and pass only the view contract needed by descendants.

View implementation ↗