@putout/plugin-react-hooks

putout plugin adds ability convert class components to hooks

Usage no npm install needed!

<script type="module">
  import putoutPluginReactHooks from 'https://cdn.skypack.dev/@putout/plugin-react-hooks';
</script>

README

@putout/plugin-react-hooks NPM version Dependency Status

putout plugin adds ability to convert class components to react hooks. Not installed with putout by default.

Install

npm i putout @putout/plugin-react-hooks -D

Add .putout.json with:

{
    "plugins": [
        "react-hooks"
    ]
}

Rules

Here is list of rules:

{
    "rules": {
        "react-hooks/remove-bind": "on",
        "react-hooks/rename-method-under-score": "on",
        "react-hooks/convert-state-to-hooks": "on",
        "react-hooks/remove-this": "on",
        "react-hooks/convert-class-to-function": "on",
        "react-hooks/convert-component-to-use-state": "on",
        "react-hooks/convert-import-component-to-use-state": "on"
    }
}

Example

Consider example using class:

import React, {
    Component,
} from 'react';
export default Button;

class Button extends Component {
    constructor() {
        super();
        
        this.state = {
            enabled: true,
        };
        
        this.toogle = this._toggle.bind(this);
    }
    
    _toggle() {
        this.setState({
            enabled: false,
        });
    }
    
    render() {
        const {enabled} = this.state;
        
        return (
            <button
                enabled={enabled}
                onClick={this.toggle}
            />
        );
    }
}

After putout --fix transform, you will receive:

import React, {
    useState,
} from 'react';
export default Button;

function Button() {
    const [enabled, setEnabled] = useState(true);
    const toggle = _toogle;
    
    function toogle() {
        setEnabled(false);
    }
    
    return (
        <button
            enabled={enabled}
            onClick={toggle}
        />
    );
}

License

MIT