Skip to content
Add support for React Hooks in your class components. Live your own life and break the rules.
JavaScript TypeScript HTML
Branch: master
Clone or download

Latest commit

Fetching latest commit…
Cannot retrieve the latest commit at this time.

Files

Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.github
example Convert to TypeScript Mar 7, 2019
src Convert to TypeScript Mar 7, 2019
.gitignore Convert to TypeScript Mar 7, 2019
CODE_OF_CONDUCT.md
CONTRIBUTING.md
LICENSE
README.md Update to 100% coverage Mar 2, 2019
package.json 3.0.1 Mar 7, 2019
tsconfig.json
yarn.lock Remove sideEffects Mar 7, 2019

README.md

🎣 with-react-hooks 🎣 GitHub license npm version Coverage Status CircleCI Status PRs Welcome

Production Ready for Enterprise Applications

Don't let the React team control your life. Take back control.

I love hooks, but it kind of sucks that they can't be used in class components. But we can fix that! This package exposes an HOC withReactHooks, that allows any hook to be used inside of a class component.

This uses actual react hooks, not just an imitation. You can directly import and use the hooks provided by the react package.

🔥🔥🔥 Now featuring a new 🔥Blazing Fast🔥 implementation. This only adds one additional component to your tree.

Installing

You probably shouldn't, but if you want to:

$ npm install with-react-hooks

Usage

import React, { useState } from 'react';
import withReactHooks from 'with-react-hooks';

class Counter extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 0
        };
    }

    render() {
        const [name, setName] = useState('');

        return (
            <div>
                {this.state.count}
                <button onClick={() => this.setState({ count: this.state.count + 1 })}>
                    +
                </button>

                <input value={name} onChange={(e) => setName(e.target.value)} />
            </div>
        );
    }
}

// Wrap with `withReactHooks` to add hook support:
export default withReactHooks(Counter);

Project Goals

When creating this project, I tried to keep these goals in mind:

  • Put hooks in classes no matter the cost.
  • Use real React hooks. No imitations, no passing props, no custom imports.
  • Support any custom hooks.
  • Support all normal class garbage.
  • Adding support to existing classes should just be one line of code (a single wrapper on the class).
  • For ease of debugging should maintain as much structure of the original component as possible.
You can’t perform that action at this time.