A Complete Introduction to React useState Hook

A simple guide to understanding and getting started with hooks

Hey there, Welcome to my first blog post. In this post, I am going to teach you what are React Hooks and how to use one of the most commonly used hooks - the useState hook

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. In the previous versions of React, functional components were known as stateless functional components because there was no way to use state and lifecycle methods in functional components.

Installation

To start using hooks, we need to install the latest version of create-react-app or you can directly create your react app without installing using the following commands:

      npm install create-react-app@latest  
      npx create-react-app my-app

Now, let's learn what are react hooks

"React hooks are the functions which allow you to use React state and lifecycle methods in functional components"

React has many built-in hooks and also allows us to create our own custom hooks. Here I am gonna teach you the most commonly used hooks.

useState Hook

This is the first hook introduced by React which allows us to use state inside the functional component. The basic syntax for calling useState hook

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

The useState hook accepts a parameter which will be the initial value of the state and returns an array of two values i.e [count,setCount] whose first value is the current value of state and the second value is the setter function which we will call with the following syntax to update the state

 <button onClick={() => setCount(count + 1)}>Increment</button>

To display the state, we directly use the count variable inside curly braces

 <p>Counter value is: {count} </p>
        <button onClick={() => setCount(count + 1)}>Increment</button>

Let's see how the complete functional component using useState would look like

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

  return (
  <>
    <div>
      <button onClick={() => setCount(count + 1)}>Increase</button>
      <button onClick={() => setCount(count - 1)}>Decrease</button>
    </div>
    <div>
      <p>Current count: {count}</p>
    </div>
  </>
  )
}

Now let us understand this by using our imagination, imagine your father as setter function and you as a state now for some reason you are angry, so angry is your first state value. but as we respect parents we have to obey what they say. so when you were angry your father told you to be calm so now your current updated state is calm.

Now, As we have understood how to use the useState Hook. Let's take an example of class-based components using state and functional components using hooks

import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {
  state = {
    counter: 0
  };

  handleOnClick = () => {
    this.setState(prevState => ({
      counter: prevState.counter + 1
    }));
  };

  render() {
    return (
      <div>
        <p>Counter value is: {this.state.counter} </p>
        <button onClick={this.handleOnClick}>Increment</button>
      </div>
    );
  }
}

Now, let's convert it into a functional component to use hooks

import React, { useState } from "react";
import ReactDOM from "react-dom";

const App = () => {
  const [counter, setCounter] = useState(0);

  return (
    <div>
      <div>
        <p>Counter value is: {counter} </p>
        <button onClick={() => setCounter(counter + 1)}>Increment</button>
      </div>
    </div>
  );
};

Don't worry if you didn't understand the difference, now I am gonna explain the above code in simple points.

  1. First to use the useState hook we need to import it as we have done in the first line.
  2. We are calling useState bypassing 0 as the initial value and using destructuring syntax, we stored array values returned by useState into counter and setCounter variables.
  3. when we click the increment button, we have defined an inline function and called the setCounter function by passing the updated counter value.
  4. As you can see we have created an inline function to update the state instead of creating a separate function to the same work because there is only a single statement in the inline function.

We can have multiple useState calls in a single functional component.

State is not merged when using the useState hook

When you use useState with an object, the state will not merge with the previous state while updating.

Let's see an example

 const [state, setState] = useState({
    counter: 0,
    username: ""
  });

Here you can see the state using objects. Now, when you want to update only the counter variable. It becomes

{counter:1}

and so the username is lost. to overcome this you have to save the previous state while updating another state. Using this syntax

setState(state=>({...state, counter:counter+1)});

Thanks for reading! your reviews are heartily welcome!