typesafe-context-hook
Version:
A react-typescript utility for creating typesafe React context hooks. It provides a function that takes a name and a hook, and returns an object with a custom hook, a provider component, and a higher-order component. The custom hook can only be used withi
49 lines (36 loc) • 851 B
Markdown
A react-typescript utility for creating typesafe React context hooks.
```bash
pnpm i typesafe-context-hook
```
```bash
npm i typesafe-context-hook
```
```bash
yarn i typesafe-context-hook
```
```tsx
import typesafeContextHook from 'typesafe-context-hook';
import { useState } from 'react';
export const { useNameContext, NameProvider } = typesafeContextHook('Name', () => {
const [name, setName] = useState('John Doe');
return { name, setName };
});
```
```tsx
// In another file
import { useNameContext, NameProvider } from './name-context.tsx';
function App() {
return (
<NameProvider>
<AnotherComponent />
</NameProvider>
);
}
function AnotherComponent() {
const { name, setName } = useNameContext();
// Now you can use name and setName in this component
}
```