An open API service indexing awesome lists of open source software.

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

Awesome Lists containing this project

README

          

# enhook [![Build Status](https://travis-ci.org/unihooks/enhook.svg?branch=master)](https://travis-ci.org/unihooks/enhook) [![unstable](https://img.shields.io/badge/stability-unstable-yellow.svg)](http://github.com/badges/stability-badges)

Enable react/preact/∀ hooks for regular functions.

[![NPM](https://nodei.co/npm/enhook.png?mini=true)](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