typesafe-context-hook
v2.0.1
Published
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
Downloads
193
Maintainers
Readme
typesafe-context-hook
A react-typescript utility for creating typesafe React context hooks.
Installation
pnpm i typesafe-context-hook
npm i typesafe-context-hook
yarn i typesafe-context-hook
Usage
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 };
});
// 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
}