Skip to content
Advertisement

How to use React with function component and hooks ONLY?

Having a React project with some component written in Class style and some others written in Hooks styles make the newcomers confuse and harder to reuse common logic. Is there a way, for example:

  • An alternative library like Preact, Inferno,… which compatible with React but only support hooks
  • Or an ESLint feature that warning every time someone try to create a React class component

to prevent my developer from writing Class component, as I want all components in my React project to be functional component with hooks only.

Advertisement

Answer

I also wanted a lint rule that accomplished this so I wrote eslint-plugin-react-prefer-function-component.

The only components that can not be written as a function component are those that implement componentDidCatch, so by default components implementing that method are allowed. This option is configurable.

eslint-plugin-react/prefer-stateless-function (mentioned in other answers) allows class components that have state or implement any class methods.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement