getStrictContext

PreviousNext

A hook that allows you to create a strict context.

Docs
animate-uilib

Preview

Loading preview…
registry/lib/get-strict-context/index.tsx
import * as React from 'react';

function getStrictContext<T>(
  name?: string,
): readonly [
  ({
    value,
    children,
  }: {
    value: T;
    children?: React.ReactNode;
  }) => React.JSX.Element,
  () => T,
] {
  const Context = React.createContext<T | undefined>(undefined);

  const Provider = ({
    value,
    children,
  }: {
    value: T;
    children?: React.ReactNode;
  }) => <Context.Provider value={value}>{children}</Context.Provider>;

  const useSafeContext = () => {
    const ctx = React.useContext(Context);
    if (ctx === undefined) {
      throw new Error(`useContext must be used within ${name ?? 'a Provider'}`);
    }
    return ctx;
  };

  return [Provider, useSafeContext] as const;
}

export { getStrictContext };

Installation

npx shadcn@latest add @animate-ui/lib-get-strict-context

Usage

import { LibGetStrictContext } from "@/lib/lib-get-strict-context"
LibGetStrictContext()