Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/ankitchouhan1020/use-context-factory
https://github.com/ankitchouhan1020/use-context-factory
Last synced: about 2 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/ankitchouhan1020/use-context-factory
- Owner: ankitchouhan1020
- Created: 2022-03-06T14:43:09.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2022-03-07T06:09:15.000Z (almost 3 years ago)
- Last Synced: 2024-11-21T23:48:33.251Z (about 2 months ago)
- Language: TypeScript
- Size: 17.6 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
## use-context-factory
This package provides an efficient way to create custom hooks for React Context api.
You may have used this pattern to create custom hooks for using context before and you might end up duplicating the code multiple times.
```js
const CounterContext = createContext(null);
export const CounterProvider = ({ children }) => {
const [ count, setCount ] = useState(0);
return (
{ children }
);
}export const useCounter = () => useContext(CounterContext);
```
This package provides a factory to create these custom hooks. [Code Sandbox Example](https://codesandbox.io/s/flamboyant-borg-8kh3bq?file=/src/App.js)
```js
const { createStateContext } from 'use-context-factory';// It can be any custom hooks that return some value to pass to provider.
const useNumberState = (init) => useState(init || 0);export const [ CounterProvider, useCount] = createStateContext(useNumberState);
///
const Parent = () => {
return (
);
}```
This pattern is mentioned in [Micro State Management with React Hooks](https://github.com/PacktPublishing/Micro-State-Management-with-React-Hooks).