What is useState hook and how do you use it?
Tags: react, webdev
Published: 2020-06-25 20:40:28

According to [React documentation](https://reactjs.org/docs/getting-started.html), **"`hooks` are special functions which enable one use state and other React features without writing ES6 classes."** There are a number of `hooks` which are part of the React Hooks API. Below are some of the most commonly used hooks.
__Basic Hooks__

- `usestate`
- `useEffect`
- `useContext`

__Advanced Hooks__

- `useReducer`
- `useCallback`
- `useMemo`
- `useRef`

This post will primarily focus on the basic `useState` hook. 

`useState`hook is a special function which takes one argument. The argument passed to `useState` is initial state. It returns an array of two entries. The first element is the initial state and the second is a function which is used for updating state.
It should be noted that unlike class components, state doesn't have to be an object. It can be a `string`, `number`, `array`, `boolean` or an `object`.

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

`const [state, setState]` is array destructuring used for unpacking elements of the array returned by `useState`. If you are not familiar with destructuring, you can read about it at [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment). You can give them meaningful names instead of `state` and `setState` for readability.

`useState` also provides an option of passing a function as an argument if the initial state has to be computed. The value returned by the function is set as initial state. In the code below i am passing a function which returns a random integer between `0` and `100` (including `0`, excluding `100`).
```javascript
const[count, setRandomCount] = useState(function generateRandomInteger(){
   return Math.floor(Math.random() * 100);
})
```
The function doesn't have to be named like i did above. You can pass an anonymous function as well, though i think a named function is better because it communicates to the reader of your code the purpose of the function.

`setRandomCount` is used for updating state just like  `this.setState` in class components with one fundamental difference. Unlike class components, it replaces current state with argument passed to `setRandomCount`. For example if the value of `count` is `50` at first render, calling `setRandomCount(10)` will change the value of `count` to `10`.

You could be wondering how to update state if it is an object. You can merge current state with changes you want to effect manually using [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). You can read more about use of spread syntax for updating state at [React Hooks FAQ](https://reactjs.org/docs/hooks-faq.html#should-i-use-one-or-many-state-variables).

The code below illustrates a simple use case of `useState`.
```javascript
import React, { useState } from "react";
import ReactDOM from "react-dom";

function App(props) {
  const [count, setRandomCount] = useState(function generateRandomInteger() {
    return Math.floor(Math.random() * 100);
  });
  function clickHandler(e) {
    setRandomCount(Math.floor(Math.random() * 100));
  }
  return (
    <div>
      <h1> {count} </h1>
      <p>
        <button onClick={clickHandler}> Click </button>
      </p>
    </div>
  );
}
const root = document.getElementById("root");
ReactDOM.render(<App />, root);
```

**NOTE**: Unlike in `class` components, you don't need `this` when using value of `state` or when assigning event handlers.

**REFERENCE**
[React Hooks Reference](https://reactjs.org/docs/hooks-reference.html)