React’s useState Hook

Manikandan Balasubramanian
3 min readAug 22, 2023

--

In React, the useState hook is a function that allows you to add state management to functional components. It’s one of the most essential hooks provided by React and enable to manage and update the state of your components without using class components.

  1. Import the Hook: First, we need to import the useState hook from the React library:
import React, { useState } from 'react';

2. To use the useState hook, we can call it with an initial value for state variable. It returns an array with two elements. The current state value and a function to update the state. it’s not a mandatory to initiate the state with initial value. it can be a empty useState function. But initiating the state with initial value will be the part of good practice.

const [name, setName] = useState('Hello');
  • name: The current value of the state variable.
  • setName: A function that allows you to update the state variable. You call this function with a new value, and React will re-render the component with the updated value.
const [name, setName] = useState('Hello');

const updateName = () => {
setName('Hello World');
};

Yes, React component will re-render the each and every state update. after the re-render process, React Component will hold the updated value not a initial value.

Object State :

  • When managing complex state that is an object, remember that useState does a shallow merge. You might need to use the spread operator or a deep merge library to update nested properties.
Object State

Also, React batches multiple setState calls together for a single render. This means that if you have multiple state updates within the same render cycle, React will optimise and re-render the component only once.

When we call the setState function multiple times within a single component function, React doesn’t immediately trigger a re-render for each individual state update. Instead, it batches or groups these state updates together and performs a single re-render for all of them.

Batching

In this example, when the “Increment Twice” button is clicked, the incrementTwice function is called, and it updates both timerCount and clockCount.

Even though we’re updating two different state variables, React still batches the state updates and performs a single render for both of them together. This means that both counts will increase by 1 after clicking the button. This batching behaviour helps optimise performance by minimizing the number of re-renders, even when there are multiple state updates happening at once.

Conclusion:

The useState hook in React provides a straightforward way to introduce and manage state in functional components, making them capable of holding and updating dynamic data over time.

--

--

No responses yet