2.0.2 • Published 1 year ago

create-use-context v2.0.2

Weekly downloads
7
License
MIT
Repository
github
Last release
1 year ago

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>
  );
}
2.0.2

1 year ago

2.0.1

1 year ago

2.0.0

1 year ago

1.0.1

5 years ago

0.0.3

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago