Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including enhook with all npm packages installed. Try it out:

var enhook = require("enhook")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

enhook v3.1.1

Enable react/preact/etc hooks for regular functions

enhook Build Status unstable

Enable react/preact/∀ hooks for regular functions.

NPM

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:

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.

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.

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 useEffects. Any subsequent calls to that function will throw an error.

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free