For working professionals
For fresh graduates
More
5. React Table
8. Context API
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.
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.
Let’s understand the importance of managing side effects with useEffects alongside state management.
`useEffect` coordinates side effects with state updates. This ensures components render accurately.
Proper management prevents issues when asynchronous tasks take longer.
Separating concerns improves code readability and maintainability.
Control over when side effects occur enhances component performance.
Isolating side effects improves the reliability and ease of testing components.
Let’s understand the advantages of “react useState” or “useState” react.
useState simplifies state management. It encapsulates state logic within functional components, and eliminates the need for class components to manage useState.
useState leverages the lightweight nature of functional components and hooks and contributes to faster rendering.
The declarative nature of useState enhances code readability.
useState promotes enables developers to create stateful logic within functional components and fosters a more modular and composable codebase.
As a built-in React hook, useState seamlessly integrates with other hooks to leverage additional functionality like useEffect and useContext.
Let’s go through the drawbacks of useState in React.
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.
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.
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.
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.
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.
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.
Write the code below at the top of your component while importing the “useState” Hook.
Import {useState} from “react.”
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);
Now, let’s understand the internal workings of a “useState” hook:
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:
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.
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:
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;
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.
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
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.