I’m trying to write a Typescript/React app, extending the React.Component
class to implement its components. All was going well until I tried to add an “effect” to a component. I found lots of documentation about useEffect
, but it all assumes the component is implemented as a function, using React.FunctionComponent
Calling useEffect
in any method in my class throws a runtime exception:
Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
I wonder if there’s any way to configure a hook in a class, or do I have to use a component function instead?
Here’s some broken code, if it’s of any use.
import React, {useEffect} from "react";
interface ViewerProps {}
interface ViewerState {}
export default class Viewer extends React.Component<ViewerProps, ViewerState> {
constructor(props: ViewerProps) {
useEffect(() => {});
super(props);
}
render = () => {
return <div id="viewer">viewer</div>
}
}