Why we cannot use hooks inside react class component ?. React Official documentation only say that hooks don't work inside class, But doesn't show why it won't work.
-
2May we know an example use-case that may necessitate hooks within class component? Also, why any such potential usage cannot be handled by using life-cycle methods? – jsN00b Jan 26 '22 at 06:19
1 Answers
Class based components are components that extend the React.Component class.
Because of this, they have access to predetermined methods and have a specific lifecycle. For example, the render()
method must be defined for class based components. More about the features of the component can be found here.
Historically, we couldn't use lifecycle methods in functional components or access state.
However, hooks were specifically introduced in React to provide this functionality to functional components. Meaning, hooks were only written for functional components when they were added.
Given the fundamental differences in the way React deals with functional components vs class based components and their different lifecycles- I suspect it wasn't feasible to try make hooks components compatible with class based components - especially as they already have access to state and their own lifecycle methods.
Moreover, given that a class component has specific methods, allowing both their existing methods and hooks would naturally lead to rendering chaos.
More can be found here on functional component lifecycle equivalents for class components.
This answer has more information on the fundamental differences and limitations of functional components vs class components - which will help elucidate why it's simple not possible to use their respective functionality in one another

- 2,786
- 2
- 18
- 33