An open API service indexing awesome lists of open source software.

https://github.com/todesstoss/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
https://github.com/todesstoss/create-use-context

context hooks react react-context react-hooks

Last synced: 10 months ago
JSON representation

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

Awesome Lists containing this project

README

          

# 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:

```sh
npm install create-use-context
```

Using Yarn:

```sh
yarn add create-use-context
```

## Screenshot

Mind the `useMyContext` return type is `NonNullable` context value

![Screenshot](Screenshot.png)

## Usage

```tsx
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>;
}

export const MyContext = createContext(null);

MyContext.displayName = 'MyContext';

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

return (

{children}

);
};

export const useMyContext = createUseContext(MyContext);

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

return (
{
setCounter(counter + 1);
}}
>
{counter} - add one

);
}

export function App() {
return (



);
}
```