@dmitriyzverev/react-ctx
v1.0.0-dev.2
Published
Simple wrapper around React.createContext, that makes it easy use hooks and context together
Downloads
86
Readme
@dmitriyzverev/react-ctx
Simple wrapper around React.createContext, that makes it easy to use hooks and context together
Usage
Install dependencies:
npm i react @dmitriyzverev/react-ctx
Just create and use context:
import React from 'react'; import {createCtx} from '@dmitriyzverev/react-ctx'; // Define a hook with your value: const useValue = () => React.useState(''); // Context factory takes any hook as the first argument: const Ctx = createCtx(useValue); // Now you can use Ctx.use() to get context value: const Input = () => { const [value, setValue] = Ctx.use(); return ( <input value={value} onChange={(e) => setValue(e.target.value)} /> ); }; const ResetButton = () => { const [, setValue] = Ctx.use(); return <button onClick={() => setValue('')}>Reset</button>; }; // Put Ctx component above in the component tree. // The Ctx component is the place where the hook is executed. const el = ( <Ctx> <Input /> <ResetButton /> </Ctx> );
Also, you can use a render function, to get a context value:
const el = ( <Ctx> {([, setValue]) => ( <> <Input /> <button onClick={() => setValue('')}>Reset</button> </> )} </Ctx> );
It is possible to pass properties to
Ctx
:interface CtxProps { initialValue: string; } const Ctx = createCtx((props: CtxProps) => { return React.useState(props.initialValue); }); const el = <Ctx initialValue="Hello!">{/* ... */}</Ctx>;
Unlike native useContext, it is impossible to use
Ctx.use()
without declaring Ctx component above in the component tree. If you try to do this:const Ctx = createCtx(() => React.useState('')); const Input = () => { const [value, setValue] = Ctx.use(); return ( <input value={value} onChange={(e) => setValue(e.target.value)} /> ); }; const el = <Input />;
You receive an error:
Context is empty. Please mount Ctx component above in the component tree.