React Hook 'useState' cannot be called in class component

avatar

Borislav Hadzhiev

Wed Apr 06 20222 min read

React Hook 'useState' cannot be called in class component #

The error "React hook 'useState' cannot be called in a class component" occurs when we try to use the useState hook in a class component. To solve the error, convert your class to a function, as hooks cannot be used in class components.

react hook usestate cannot be called in class

Here is an example of how the error occurs.

App.js
import {useState, useEffect} from 'react'; class Example { render() { // ⛔️ React Hook "useState" cannot be called in a class component. // React Hooks must be called in a React function component or a custom React Hook function. const [count, setCount] = useState(0); // ⛔️ React Hook "useEffect" cannot be called in a class component. // React Hooks must be called in a React function component or a custom React Hook function. useEffect(() => { console.log('hello world'); }, []); return ( <div> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } }
The error is caused because hooks can only be used inside of function components or custom hooks and we're trying to use hooks inside of a class.

One way to solve the error is to convert the class to a function component.

App.js
import {useState, useEffect} from 'react'; export default function App() { const [count, setCount] = useState(0); useEffect(() => { console.log('hello world'); }, []); return ( <div> <h2>Count {count}</h2> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }

Like the documentation states:

  • Only call hooks from React function components or from custom hooks.
  • Only call hooks at the top level
  • Don't call hooks inside loops, conditions or nested functions
  • Always use hooks at the top level of your React function, before any early returns

Alternatively, we can use a class component and update the state with the setState() method.

App.js
import React from 'react'; export default class App extends React.Component { constructor(props) { super(props); this.state = { count: 0, }; } render() { return ( <div> <h2>Count: {this.state.count}</h2> <button onClick={() => this.setState({count: this.state.count + 1})}> Increment </button> </div> ); } }

Note that function components are used more often than classes in newer codebases.

They are also more convenient because we don't have to think about the this keyword and enable us to use built-in and custom hooks.

Use the search field on my Home Page to filter through my more than 1,000 articles.