https://github.com/nksaraf/create-hook-context
A better and more powerful React.createContext powered by hooks 🎣
https://github.com/nksaraf/create-hook-context
context react react-context react-hooks
Last synced: about 2 months ago
JSON representation
A better and more powerful React.createContext powered by hooks 🎣
- Host: GitHub
- URL: https://github.com/nksaraf/create-hook-context
- Owner: nksaraf
- License: mit
- Created: 2020-04-24T00:52:26.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2020-04-29T19:00:38.000Z (over 5 years ago)
- Last Synced: 2025-03-06T06:20:02.929Z (7 months ago)
- Topics: context, react, react-context, react-hooks
- Language: TypeScript
- Homepage:
- Size: 139 KB
- Stars: 2
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# create-hook-context
A more powerful version of `React.createContext`. Accepts a hook function that takes in props for a Provider and then the returned value of the hook is the value provided to the Context's consumers.
Given hook `(props: TProviderProps) => TContext`, returns utilities as an array `[ContextProvider, useContext, withContextProvider, Context]` to consume this context:
* `ContextProvider`: Takes in `TProviderProps` and provides a context `TContext`, eg.
```tsx
```
* `useContext`: Returns the wrapped `TContext`, eg.
```tsxconst context = useContext()
```
* `withContextProvider`: Can be used to wrap a component with a `ContextProvider`, eg.
```tsxconst App = withContextProvider(props)(() => {
const context = useContext();
return{JSON.stringify(context)};
});
```
* `Context`: Context created by React### Example:
```javascript
import createContext from 'create-hook-context';
const [ThemeProvider, useTheme, withThemeProvider, ThemeContext] = createContext(
({ theme }) => theme, // hook that provides values for context given input
{}, // defaultValue for context
"Theme" // displayName for Context
)const Consumer = () => {
const val = useTheme();
return{JSON.stringify(val)};
};const App = () => {
return (
);
};/* or can use withThemeProvider to wrap components */
const App = withThemeProvider({ theme: { a: 1 } }, () => {
const val = useTheme();
return{JSON.stringify(val)};
});```