Hooks should not only be allowed inside the body of a function component.
See original GitHub issueDo you want to request a feature or report a bug? feature
What is the current behavior?
Using hooks in class component return the Hooks can only be called inside the body of a function component.
error message
What is the expected behavior? I’d like to be able to use hooks in functional component AND in class component.
Actually in our team we declare all our component as class component. Since we have a lot a new developper incoming, and some of them are react beginners, we wanted to offer a homogeneous codebase, with code generator (using plop). Is it a bad practice ? Because we can’t use hooks, the way they are actually implemented.
Of course, we can use lifecycle and state without hooks. But if we want to use a hooks developed by another libraries, like https://react.i18next.com/experimental/using-with-hooks, we can’t.
I even asking myself, will class component will be deprecated ? 😲
Issue Analytics
- State:
- Created 5 years ago
- Comments:6 (1 by maintainers)
From the React team’s perspective, I’d argue that class components are considered more of a barrier to React’s adoption than functional components because class components tend to be messier than functional components and require an understanding of how
this
works in javascript.Hooks are explicitly designed to work only inside of functional components (or inside of other hooks). If class components supported hooks too, it would add unnecessary overhead and make class components even more confusing.
Restricting your team to class-based components is doing a disservice to your new developers. While a homogeneous code base can be great for onboarding and developer productivity, it shouldn’t preclude the use of functional components. There are many cases in which it is better to use functional component over a class component. Knowing what those cases look like and why you choose one approach over another is an important exercise that your new developers should undertake.
Finally, the i18next library that you linked to offers a HOC component that you can use in place of a hook. I don’t know how that will fair with your new developers, but it will give you access to the functionality that you are seeking for class components.
I think your position is built off of a bad assumption. A hook should never have to be rewritten as a class component. The React team has already figured out how to support most class features with hooks and is closing in on the remaining few items. Even if that wasn’t the case, you could always nest a class component inside of a functional component to leverage class features. For example,
Setting that aside, I think the more fundamental issue with your request is that you are asking for a convenience feature that comes at the expense of performance and the promotion of best practices. Why would this feature be net-beneficial for the React community?