React State Hook

In React, state Hooks is the new way of working with states. A hook is a special function that lets you 'hook into' React features.


Using State Hooks

useState is a hook that lets you add React state to your functional components. It enables you to set and retrieve state.

To start using the State Hook, import your components as:


  import React, { useState } from 'react';


After importing it, you will have to destructure two values of it:


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


The argument passed to the useState() is the initial state. It's the same like we have this in class components:


  this.state = {
    count:0
  }


The useState() returns two bindings: the actual state value, and the state updating function (like we have setState in class Components).

So a component with hooks will look like this:


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


So in the first line, we are importing the useState hook. It is then destructured inside the functional component. count is the inital state value, and setCount is a method for updating the state.


Arrays as initial state values

This is how we can initialize a state variable as an empty array:


  const [count, setCount] = useState([]);


Same goes for the object as well. You can define the state variable as an empty object like this:


  const [count, setCount] = useState({});