https://github.com/dy/enhook
Enable hooks for a function
https://github.com/dy/enhook
hooks hooks-api-react reactive unihooks
Last synced: 6 months ago
JSON representation
Enable hooks for a function
- Host: GitHub
- URL: https://github.com/dy/enhook
- Owner: dy
- License: mit
- Created: 2019-10-31T23:24:19.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2023-01-04T23:55:23.000Z (about 3 years ago)
- Last Synced: 2024-12-28T06:41:52.252Z (about 1 year ago)
- Topics: hooks, hooks-api-react, reactive, unihooks
- Language: JavaScript
- Homepage:
- Size: 2.06 MB
- Stars: 25
- Watchers: 3
- Forks: 0
- Open Issues: 20
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# enhook [](https://travis-ci.org/unihooks/enhook) [](http://github.com/badges/stability-badges)
Enable react/preact/∀ hooks for regular functions.
[](https://nodei.co/npm/enhook/)
```js
import enableHooks from 'enhook'
import { useState, useEffect } from 'any-hooks'
let countFrom = enableHooks(initCount => {
let [count, setCount] = useState(initCount)
setTimeout(() => {
setCount(++count)
}, 1000)
// any side-effects
useEffect(() => console.log(count), [count])
})
countFrom(0)
```
_Enhook_ turns any function into reactive function with enabled hooks for a given framework.
The framework is by default detected from the list:
* [x] [`react`](https://ghub.io/react)
* [x] [`preact`](https://ghub.io/preact)
* [x] [`rax`](https://ghub.io/rax)
* [x] [`haunted`](https://ghub.io/haunted)
* [x] [`augmentor`](https://ghub.io/augmentor)
* [x] [`atomico`](https://ghub.io/atomico)
* [x] [`fuco`](https://ghub.io/fuco)
* [x] [`tng-hooks`](https://ghub.io/tng-hooks) (passive)
In case of ES modules autodetection is not available (until `import.meta.resolve()` or `await import()` is available), you have to manually indicate framework to use.
```js
import * as preact from 'preact'
import preactHooks from 'preact/hooks'
import enhook from 'enhook'
import setHooks, { useState } from 'any-hooks'
enhook.use(preact) // or enhook.use(React, ReactDOM)
setHooks(preactHooks)
// now enhook uses preact with as base
let fn = enhook(() => {
let [count, setCount] = useState(0)
//...
})
```
## API
### `fn = enhook(fn, { passive=false }?)`
Create function wrapper, allowing hooks in function body. `passive` option may define if function must be reactive.
```js
import enhook from 'enhook'
import { useState } from 'any-hooks'
let passiveFn = enhook((i) => {
let [count, setCount] = useState(0)
// this does not cause self-recursion in passive mode
setCount(i)
}, { passive: true })
passiveFn(1)
passiveFn(2)
```
#### `fn.unhook()`
Teardown enhooked function. This will dispose all `useEffect`s. Any subsequent calls to that function will throw an error.
## See also
* [unihooks](https://github.com/unihooks/unihooks) - unified all-framework essential hooks collection.
## License
MIT
HK