create-use-context
TypeScript icon, indicating that this package has built-in type declarations

2.0.2 • Public • Published

create-use-context

A helper method which wraps original React useContext method in a type-safe manner providing NonNullable context value. Will throw if used outside of Provider

Installation

Using NPM:

npm install create-use-context

Using Yarn:

yarn add create-use-context

Screenshot

Mind the useMyContext return type is NonNullable context value

Screenshot

Usage

import React, { createContext, useState, FC, Dispatch, SetStateAction } from 'react';
import { createUseContext } from 'create-use-context';

type Counter = number;

const INITIAL_COUNT: Counter = 0;

export interface MyContextValue {
  counter: Counter;
  setCounter: Dispatch<SetStateAction<Counter>>;
}

export const MyContext = createContext<MyContextValue | null>(null);

MyContext.displayName = 'MyContext';

export const MyContextProvider: FC = ({ children }) => {
  const [counter, setCounter] = useState(INITIAL_COUNT);

  return (
    <MyContext.Provider value={{ counter, setCounter }}>
      {children}
    </MyContext.Provider>
  );
};

export const useMyContext = createUseContext(MyContext);

export function ComponentWithHook() {
  const { counter, setCounter } = useMyContext();

  return (
    <button
      onClick={() => {
        setCounter(counter + 1);
      }}
    >
      {counter} - add one
    </button>
  );
}

export function App() {
  return (
    <MyContextProvider>
      <ComponentWithHook />
    </MyContextProvider>
  );
}

Package Sidebar

Install

npm i create-use-context

Weekly Downloads

11

Version

2.0.2

License

MIT

Unpacked Size

6.17 kB

Total Files

11

Last publish

Collaborators

  • dirgen