View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

React useState Hook

Updated on 30/01/2025459 Views

The "useState" in React is an addition to React.js, introduced in the 16.8 version. It enables the developer to manage the state within functional components without the need for a class-based component.

In this article, we will focus on state hooks, their syntax, and best practices with examples.

In React, the useState hook serves as a powerful tool that enables developers to integrate state management seamlessly within functional components.

This means you can store and update data within a component without the need for class-based syntax or lifecycle methods.

What is useState in React?

Prior to the introduction of the useState in React version 16.8, functional components were limited in their ability to maintain the useState. Developers resorted to using class components for state management, which often lead to verbose and complex code.

With the advent of the use of State, functional components gained the capability to handle it in a concise and intuitive manner.

Managing Side Effects with useEffects

Let’s understand the importance of managing side effects with useEffects alongside state management.

Synchronization

`useEffect` coordinates side effects with state updates. This ensures components render accurately.

Race Conditions

Proper management prevents issues when asynchronous tasks take longer.

Clean Code

Separating concerns improves code readability and maintainability.

Performance Optimization

Control over when side effects occur enhances component performance.

Testability

Isolating side effects improves the reliability and ease of testing components.

Benefits of “React UseState”

Let’s understand the advantages of “react useState” or “useState” react.

Simplified State Management

useState simplifies state management. It encapsulates state logic within functional components, and eliminates the need for class components to manage useState.

Enhanced Performance

useState leverages the lightweight nature of functional components and hooks and contributes to faster rendering.

Improved Code Readability

The declarative nature of useState enhances code readability.

Encourages Functional Programming

useState promotes enables developers to create stateful logic within functional components and fosters a more modular and composable codebase.

Hooks Compatibility

As a built-in React hook, useState seamlessly integrates with other hooks to leverage additional functionality like useEffect and useContext.

Drawbacks of useState React

Let’s go through the drawbacks of useState in React.

Incorrect Array Updates

When updating arrays with useState, array functions like `push()` may not trigger re-renders. Instead, spread operators should be used to create new array references.

Immutable Updates for Objects

Similar to arrays, directly mutating objects may lead to issues. It's better to create new object references using spread syntax or libraries like `immer` for complex state updates.

Stale State with Asynchronous Updates

When updating state asynchronously (e.g., with `setTimeout` or `fetch`), closures might capture stale values. To avoid this, use functional updates or `useEffect` dependencies properly.

State Bloat

Overusing useState for every piece of local state can lead to bloated components. Consider splitting state into smaller, more focused pieces or using context and reducers for global state management.

Performance Overhead

While useState is efficient for small-scale state management, excessive usage in deeply nested components or large-scale applications can impact performance. Evaluate if the state needs to be hoisted or shared between components to optimize performance.

Syntax of “useState” React

The syntax of useState is straightforward. It follows a simple pattern:

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

Here, useState returns a pair: the current state value (State) and a function (setState) that allows you to update it. The initialState parameter is optional and sets the initial value of the useState. useState can be used to manage booleans, strings, numbers, arrays, and objects. By invoking the setState function returned by useState, you can update the state value and trigger a re-render of the component.

Importing the useState Hook

Write the code below at the top of your component while importing the “useState” Hook.

Import {useState} from “react.

Structure of the “useState” Hook

The Hook takes some initial state and returns two values. The first one contains the useState, and the second one is a function that updates the useState. The value passed in this useState will be considered the default value.

Syntax
const [var, setVar] = useState(0);

Internal Working of “useState” Hook

Now, let’s understand the internal workings of a “useState” hook:

  • A useState builds a new cell in the memory object of the functional component.
  • During rendering, a new state value is stored in this cell
  • The stack pointer figures out the latest cell after each render.
  • A purposeful user refresh triggers the stack dump.
  • The memory cell protects the useState between two renders, ensuring persistence.

What are the useState Hook examples in React?

Example 1: Using a useState Hook

// Filename - App.js
import React, { useState } from 'react';
function App() {
const click = useState('GeeksForGeeks');
return (
<h1>Welcome to {click}</h1>
);
}
export default App;

Output:

  • useState() returns the initial value of the state, and a function to change it.
  • When you use array destructuring, you can easily assign values from the array returned by useState() to separate variables.
  • You can assign values from the useState() array individually using their indexes, like the first value at index 0 and the second value at index 1.

Updating State in useState

To change or update the State using useState, you need to use the second function that comes back from the useState hook. When you call the function, it updates the first thing, which is the State itself.

Syntax
setVar(newState);

Example 1: Updating React useState Hook State

This example shows how to use a particular variable to remember things in a part of our program. To change the particular variable, we use a function that comes with it to make the change.

// Filename - App.js import React,
{ useState } from 'react'; function App()
{ const [click, setClick] = useState(0);
// using array destructuring here
// to assign initial value 0 // to click and a reference to the function
// that updates click to setClick return (
You clicked {click} times
setClick(click + 1)}> Click me
); } export default App;

Example 2: React useState Previous Hook

Here's a simple program that shows how to use a variable's current value when updating it to a new value.

// Filename - App.js
import React, { useState } from 'react';
function App() {
const [click, setClick] = useState(0);
return (
<div>
<p>You've clicked {click} times!</p>
<p>The number of times you have clicked
is {click % 2 == 0 ? 'even!': 'odd!'}</p>

<button onClick={() => setClick(click => click + 1)}>
Click me
</button>
</div>
);
}
export default App;

Output:

In the above example, the arrow function inside setClick() gets the previous value of the click variable. This is helpful as it allows us to change the data based on what the State currently is. This is particularly useful when the new State relies on what the State was before.

Updating Arrays and Objects Using the “useState” Hook

Sometimes, we only want to change one piece of information in a state object instead of replacing the whole thing. We use the spread operator (...) to grab the existing values and then add the new value we want to update.

Example 1: React useState Hook Array

The program or code to generate the use of Arrays as a state variable.

// Filename - App.js
import React, { useState } from 'react';
function App() {
const [click, setClick] = useState([]);
const addNumber = () => {
setClick([
...click,
{
id: click.length,
value: Math.random() * 10
}
]);
};
return (
<div>
<ul>
{click.map(item => (
<li key={item.id}>{item.value}</li>
))}
</ul>
<button onClick={addNumber}>
Click me
</button>
</div>
);
}
export default App;

Output:

  • `useState()` works differently from `setState()` in class components, especially with arrays.
  • When using `setClick()` in `useState()`, it replaces array values instead of adding to them.
  • To add new numbers to an array without losing the existing ones, we use the spread operator (...) in `addNumber().`
  • Using objects for handling different types of data makes our code more organized, scalable, and easier to maintain with fewer `useState()` calls.
  • Objects help us see a component's entire useState, making it easier to understand and work with specific data.

Example 2: React useState Hook Object

The syntax to use the React useState Hook Object is as below:

// Filename - App.js
import React, { useState } from 'react';
function App() {
const [data, setData] = useState({
username: '',
password: ''
});
const [form, setForm] = useState({
username: '',
password: ''
});
const [submit, submitted] = useState(false);
const printValues = e => {
e.preventDefault();
setForm({
username: data.username,
password: data.password
});
submitted(true);
};
const update field = e => {
setData({
data,
[e.target.name]: e.target.value
});
};
return (
<div>
<form onSubmit={printValues}>
<label>
Username:
<input
value={data.username}
name="username"
onChange={updateField}
/>
</label>
<br />
<label>
Password:
<input
value={data.password}
name="password"
type="password"
onChange={updateField}
/>
</label>
<br />
<button>Submit</button>
</form>
<p>{submit ? form.username : null}</p>
<p>{submit ? form.password : null}</p>
</div>
);
}
export default App;
  • The 'data' variable temporarily records the username and password entered by the user. It uses the spread operator (...) to update the existing values.
  • After the user submits the form, the values they entered are shown below the form.
  • The existing values in the fields are copied and then updated based on the user type.
  • When 'setForm()' is used to update the 'form' state variable, it doesn't use the spread operator. This means it doesn't consider the previous values.
  • By not using the spread operator in 'setForm()', managing the State is simpler because the past username and password values are no longer important.

FAQs

1. What is the use of useState and useEffect?

`useState` manages stateful data in functional components, while `useEffect` handles side effects like data fetching or DOM manipulation.

2. What is a state variable in React?

A state variable in React is a data point that can change over time. It affects the behavior and appearance of components.

3. What is the difference between setState and useState?

`setState` is used in class components to update State. `useState` is a hook used in functional components for the same purpose.

4. How does useState work?

`useState` returns a stateful value and a function to update it. It re-renders the component when the State is updated.

5. Why is useState called twice in React?

`useState` isn't called twice but returns an arrangement with the current state value and a function to update it.

6. What are Hooks in React?

Hooks in React enable functional components to use State and other React features without needing class components.

image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.