头图

The text starts here~

Overview

When we try to use the useState hook in a class component, the error "React hook 'useState' cannot be called in a class component" is generated. To resolve the error, convert the class component to a function component. Because hooks cannot be used in class components.

react-hook-usestate-cannot-be-called-in-class.png

Here is an example to show 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 reason for this error is that hooks can only be used in function components or custom hooks and we are trying to use hooks in a class.

functional component

One way to resolve this error is to convert class components to function components.

 // 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>
  );
}

As the documentation says:

  • Only call Hooks from React function components or custom hooks
  • Only use hooks at the top level
  • Don't call Hooks in loops, conditionals or nested functions
  • Make sure to always use Hook at the top level of your React function and before any return

Use setState() in class components

Alternatively, we can use a class component to 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 in newer codebases, function components are used more often than classes.

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.


chuck
303 声望41 粉丝