context-hook
v1.0.10
Published
Simple util that resolves common cases with react Context API.
Downloads
24
Maintainers
Readme
React Context Hook Builder
Simple util that resolves common cases with react Context API.
Util generates provider and hook dynamically from passed name.
Installation
npm install context-hook
yarn add context-hook
Usage
Create context
/*
* useCounter.ts
*/
import { useState } from 'react';
import { createContextHook } from 'context-hook';
type Props = {
defaultCount: number;
}
// Or you can create without props
const useCounterLocal = (props: Props) => {
const [count, setCount] = useState(payload.defaultCount);
const increment = () => setCount((prev) => ++prev);
const decrement = () => setCount((prev) => --prev);
return [count, increment, decrement];
};
export const { CounterProvider, useCounter } = createContextHook('Counter', useCounterLocal) ;
Connect to UI
/*
* SomeUi.tsx
*/
import { useCounter } from './useCounter';
import { SomeUiComponent } from './SomeUiComponent';
const SomeUi: React.VFC = () => {
return (
<CounterProvider defaultCount={2}>
<SomeUiComponent />
</CounterProvider>
);
};
Use
/*
* SomeUiComponent.tsx
*/
import { useCounter } from './useCounter';
export const SomeUiComponent: React.VFC = () => {
const [count, increment, decrement] = useCounter();
// - Count: 2 +
return (
<div>
<button onClick={increment}>-</button>
<p>Count: {count}</p>
<button onClick={decrement}>+</button>
</div>
);
};