Skip to content

Documentation / @andrew_l/context / createContext

Function: createContext()

createContext<ContextValue>(providerName, contextName?): readonly [<T>(fallback?) => T extends null ? null | ContextValue : ContextValue, (contextValue) => ContextValue]

Wrapper around provide/inject function to simple usage.

Type Parameters

ContextValue

Parameters

providerName: string | string[]

The name(s) of the providing the context.

There are situations where context can come from multiple scopes. In such cases, you might need to give an array of names to provide your context, instead of just a single string.

contextName?: string

The description for injection key symbol.

Returns

readonly [<T>(fallback?) => T extends null ? null | ContextValue : ContextValue, (contextValue) => ContextValue]

Example

ts
const [injectTraceId, provideTraceId] = createContext<string>('withContext');

// this function will returns the same trace if for execution context
export const useTraceId = () => {
  let traceId = injectTraceId(null);

  if (!traceId) {
    traceId = uuidv4();
    provideTraceId(traceId);
  }

  return traceId;
};