The useState Hook

Consider the following class component:

import { Component } from "react";

class App extends 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>
    );
  }
}

export default App;

Here is the same component, but it is written as a function!

import { useState } from "react";

function App (props) {
  const [count, setCount] = useState(0);
  
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

export default App;

The useState Hook takes the initial state as an argument (we passed 0). It returns an array with two elements: the current state (count) and a function to change the state (setCount).

The general syntax for employing useState is:

const [state, setState] = useState(initialState);

The useState Hook returns an array. The bracket syntax [state, setState] to the left of the equal sign is array destructuring.

The state variable always contains the (latest) state. To update the state, you must use the setState function. Only then React will know the state has been updated, and it will re-render the UI.

With useState, it's common to name the returned values like foo and setFoo, but you can call them whatever you like. If you are from the OOP world, it might help to think about these two as a "getter" and a "setter" for an attribute!

The useState is a JavaScript function built into the React library. You must import it before using it.

import { useState } from "react";

So, how does this work under the hood? When you use Hooks in a function component, React creates an object to live alongside it. In this object, React stores the state (and other metadata) about the component. There is no magic! It's a hack to allow you to use "state" with functions, a programming construct that is naturally stateless!