react
hook_error
ai_generated
true
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. (class component)
ID: react/hooks-in-class-component
90%Fix Rate
92%Confidence
50Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 18 | active | — | — | — |
Root Cause
Using hooks (useState, useEffect) in a class component. Hooks are function-component only.
genericWorkarounds
-
95% success Convert class component to function component to use hooks
// Class: this.state, this.setState // Function: const [state, setState] = useState()
Sources: https://react.dev/reference/react/Component#alternatives
-
85% success If keeping class, use lifecycle methods instead: componentDidMount, componentDidUpdate
Replace componentDidMount with useEffect(() => {...}, []) and componentDidUpdate with useEffect(() => {...}, [deps])Sources: https://react.dev/reference/react/Component#componentdidmount
Dead Ends
Common approaches that don't work:
-
Wrap class component in a function component
65% fail
Over-engineering — convert the class component instead
-
Use a higher-order component to inject hooks
50% fail
Works but adds complexity — better to convert to function component
Error Chain
Frequently confused with: