useState

A Hook that lets you add React state to function components.

  • Before the useState hook was introduced, state management is used to handle through the class components.

class Counter extends React.Component {
  constructor(props) {
    this.state = {
      count: 0      // initially the count is set to 0
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me        // this.setState will increase the count by 1 everytime
        </button>
      </div>
    );
  }
}
  • Now, the useState hook can be used in functional components which serves the same purpose as this.state/this.setState in class components as shown above.

import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
  • using the useState hook, any type of state variable can be declared.

  • the hook can also be used multiple times in a single component.

Last updated