@dmitriyzverev/react-ctx
v1.0.0-dev.1
Published
Simple wrapper around React.createContext, that makes it easy use hooks and context together
Downloads
7
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 context provider above in the component tree. // The provider is the place where the hook is executed. const el = ( <ctx.Provider> <Input /> <ResetButton /> </ctx.Provider> );
Also, you can use a render function, to get a context value:
const el = ( <ctx.Provider> {([, setValue]) => ( <> <Input /> <button onClick={() => setValue('')}>Reset</button> </> )} </ctx.Provider> );
It is possible to pass properties to
ctx.Provider
:interface ProviderProps { initialValue: string; } const ctx = createCtx((props: ProviderProps) => { return React.useState(props.initialValue); }); const el = <ctx.Provider initialValue="Hello!">{/* ... */}</ctx.Provider>;
Unlike native useContext, it is impossible to use
ctx.use()
without declaring a provider. 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 will get an error:
Context is empty. Please mount ctx.Provider component above in the component tree.