Unable to use useState in class component React.js

In react, we have 2 ways to build components: classes and functions.

DOCS

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

Using the State Hook:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Equivalent Class Example:

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

Officially you can't use hook on class component. But of course there is some trick if you want use useState on class component

example, you can't do this

class Example extends React.Component {

  _renderCounter = () => {
    //
    // YOU CAN'T DO THIS
    // REACT WONT ALLOW YOU
    //
    const [count, setCount] = useState(0);
    return <div>{ count }</div>
  }

  render() {
    return(
      <div>{ this._renderCounter() }</div>
    );
  }
}

But, with small trick you can do this. React will allow you

class Example extends React.Component {

  _renderCounter = () => () => {
    const [count, setCount] = useState(0);

    return <div>{ count }</div>
  }

  render() {
    const MyInlineHook = this._renderCounter();

    return(
      <div><MyInlineHook /></div>
    );
  }
}

With this trick, you can access to this and props of the class component. :)


Hooks can only be used in functional components, you're using class component.

For more information and how to implement it please check this article Link


You are trying to use useState, which is a React hook, inside a class component. This won't work. Hooks can only be used in functional components.

Tags:

Reactjs