Last updated: Apr 6, 2024
Reading time·2 min
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.
Here is an example of how the error occurs.
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> ); } }
One way to solve the error is to convert the class to a function component.
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:
setState()
in a class componentAlternatively, we can use a class component and update the state with the
setState()
method.
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.