https://github.com/lfarrel6/react-instant-hook
A lightweight module to instantly create hooks for your contexts
https://github.com/lfarrel6/react-instant-hook
context-api-react hooks-api-react npm-module npm-package react reactjs
Last synced: 3 months ago
JSON representation
A lightweight module to instantly create hooks for your contexts
- Host: GitHub
- URL: https://github.com/lfarrel6/react-instant-hook
- Owner: lfarrel6
- License: mit
- Created: 2020-04-30T18:41:20.000Z (about 5 years ago)
- Default Branch: master
- Last Pushed: 2023-01-06T04:58:01.000Z (over 2 years ago)
- Last Synced: 2024-04-25T13:21:07.515Z (about 1 year ago)
- Topics: context-api-react, hooks-api-react, npm-module, npm-package, react, reactjs
- Language: JavaScript
- Size: 804 KB
- Stars: 4
- Watchers: 0
- Forks: 0
- Open Issues: 13
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# react-instant-hook
A lightweight module to instantly create hooks for your contexts# Motivation
I find that hooks make for much cleaner components in react, and custom context hooks maximise the readability. Writing these custom context hooks ends up being largely boilerplate (`useContext`, validate something is returned, return the value).This module removes that boilerplate, and lets you create custom hooks for your context with one line.
# Install
`npm i react-instant-hook`# Usage
Simply declare your contexts as normal, and then pass them into `getHook` to receive your context hook.`getHook` can also take a validation function as a second parameter, which you can use to force errors when using your hook inappropriately.
The default validation throws an Error if the value is undefined (assumes you are using it outside of a provider)## Example
Declare your context and pass it into `getHook`
```js
// SampleContext.jsimport React from 'react';
import { getHook } from 'react-instant-hook';export const SampleContext = React.createContext(undefined);
export const SampleContextProvider = ({ children }) => (
{children}
);
export const useSample = getHook(SampleContext);
```Then use the context with your custom hook
```js
// SampleComponent.jsimport React from 'react';
import { SampleContextProvider, useSample } from './SampleContext';const SampleComponent = () => {
const { number } = useSample();return
The magic number is: {number}
}export default () => (
);
```