Eslint-plugin-react: Rule Proposal: prefer-hook-component

Created on 6 Mar 2019  路  4Comments  路  Source: yannickcr/eslint-plugin-react

With hooks being introduced on React 16.8, it would be nice and helpful to have a rule to use _hooked_ functional components rather than _stateful_ class components.

This will generate warnings/errors

class Switch extends React.Component {
  state = {
    isOn: false
  }

  toggle = () => {
    this.setState(state => ({ isOn: !state.isOn }))
  }

  render () {
    return (
      <div>
        <div>Switch is {this.state.isOn ? 'ON' : 'OFF'}</div>
        <button onClick={this.toggle}>Toggle</button>
      </div>
    )
  }
}

This will not generate errors

function Switch() {
  const [isOn, setIsOn] = useState(false);
  const toggle = useCallback(() => setIsOn(!isOn), [isOn]);

  return (
    <div>
      <div>Switch is {isOn ? "ON" : "OFF"}</div>
      <button onClick={toggle}>Toggle</button>
    </div>
  );
}

Of course, this should depend on settings.react.version >= 16.8

new rule question

Most helpful comment

I very much doubt this is a good idea; many class components should be class components, and should not be hooked SFCs.

@gaearon, what do you think about this rule?

All 4 comments

If we were to do this, the rule should at least look for componentDidCatch and getSnapshotBeforeUpdate as those are not supported by hooks.

Personally I would probably not use this rule right now. I think it's premature given that it's explicitly not recommended to go and refactor all your classes to hooks-based components. I guess it might have some merit if you're starting a new project and writing all your new components with hooks.

@alexzherdev sure, that's why I'd proposed to check if the react version supports hooks.

To be honest, I think maybe not everyone will be refactoring existing applications to hooks, but at least the majority will be using them on new apps.

Or maybe a company wants to enforce the use of hooks and a new developer doesn't now about this convention, then he will have a warning (or error, depending on the configuration) about it.

I very much doubt this is a good idea; many class components should be class components, and should not be hooked SFCs.

@gaearon, what do you think about this rule?

Did anyone created there own eslint plugin for it?
I wanted to enforce( with warning) to use hooks on our project.
Hooks makes the code much cleaner, and much more predictable.

Was this page helpful?
0 / 5 - 0 ratings