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
- Host: GitHub
- URL: https://github.com/todesstoss/create-use-context
- Owner: todesstoss
- License: mit
- Created: 2019-05-22T14:23:05.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2024-09-26T13:55:23.000Z (over 1 year ago)
- Last Synced: 2025-04-16T00:57:44.568Z (10 months ago)
- Topics: context, hooks, react, react-context, react-hooks
- Language: JavaScript
- Homepage:
- Size: 146 KB
- Stars: 7
- Watchers: 3
- Forks: 1
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
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

## 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 (
);
}
```