Skip to content

createReactiveContext ​

Creates a typed context selector with optimized updates for state selection

helpers
test coverage
Last changed: 23 days ago

WARNING

For complex interfaces, we strongly recommend using state management solutions outside of React like createStore, reatom, effector, or zustand instead of context

Installation ​

Library
CLI
Manual
typescript
import { createReactiveContext } from '@siberiacancode/reactuse';

Usage ​

typescript
const { Provider, useSelector, instance } = createReactiveContext<number>(0);

Demo ​

Api ​

Parameters

NameTypeDefaultNote
defaultValue?Value | undefined-- Default value for the context
options?CreateReactiveContextOptions<Value>-- Additional options for context creation

Returns

CreateReactiveContextReturn<Value>

Type declaration ​

typescript
import type { Context, FC, Provider, ProviderProps, RefObject } from 'react';

export interface CreateReactiveContextOptions {
  /** Display name for the context (useful for debugging) */
  name?: string;
  /** Whether to throw an error if context is used outside of Provider */
  strict?: boolean;
}

export interface CreateReactiveContextReturn<Value> {
  /** The context instance */
  instance: Context<ReactiveContextValue<Value>>;
  /** The Provider component for the context */
  Provider: Provider<Value>;
  /** A hook to select a part of the context state */
  useSelector: <Selected>(selector?: (state: Value) => Selected) => Selected;
}

type ContextListener<Value> = (value: Value) => void;

interface ReactiveContextValue<Value> {
  /** The listeners for the context */
  listeners: Set<ContextListener<Value>>;
  /** The value for the context */
  value: RefObject<Value>;
}

Source ​

Source • Demo

Contributors ​

D
debabin
debabin

Released under the MIT License.