function contextKeyFor
Since 0.2.0
contextKeyFor<T>(
name: string,
defaultValue: T
): RouterContextKey<T>

Returns the context key for a name, creating it on first use.

Use this instead of writing { defaultValue: … } by hand whenever a key is SET in one module and READ in another that a bundler may duplicate — which, in a framework-mode application, is every key an application declares for itself. Both sides resolve the name through this module, so they receive the identical object however many times their own modules are copied.

That only holds while this package is a single module instance. In a scaffolded project it is: the server build treats @setu-ts/* as external, so the bundle imports this module at runtime rather than inlining a second copy of it.

Examples

An application-declared key, set in setu.config.ts and read in a loader

import { contextKeyFor } from '@setu-ts/react-router-plugin';
import type { ISession } from '@setu-ts/common';

export const sessionContext = contextKeyFor<ISession | null>('session', null);

Type Parameters

The value the key carries

Parameters

name: string

A stable, application-wide unique name for the key

defaultValue: T

Returned by context.get() before anything sets the key. Required, because React Router throws for an unset key that has none.

Return Type

The key for that name — the same object on every call

Usage

import { contextKeyFor } from "react-router-plugin/src/index.ts";