For working professionals
For fresh graduates
More
5. React Table
8. Context API
Let us understand the concept of useState with a simple example. Imagine planning a dinner party for friends and writing down the items you need to purchase. Consider useState in React as your mental note-taking process in this scenario. Initially, your list is empty, just like the initial state in React components. As you remember the items you need, you add them to your list similar to updating the state with useState. If you realize you already have an item or don't need it, remove it from your list, mirroring state updates in React. Additionally, if you have purchased an item, you mentally check it off your list, similar to how useState can manage boolean flags to track whether an item is purchased. With each addition, removal, or modification, your shopping list dynamically updates, just as React components update their state, ensuring your dinner party planning process—and your React application—remain organized and responsive to your needs.
React, a JavaScript library for building user interfaces, introduced Hooks in version 16.8. useState is one of the most fundamental Hooks provided by React. It enables functional components to manage state without the need for class components. In this tutorial, we will explore the effective use of useState in React applications.
useState is a hook that allows you to add state to functional components. It takes a single argument that is the initial sate and returns an array containing the current state value and a function to update it.
Before Hooks, state management in React was primarily achieved using class components. However, class components can be complex and more challenging to understand, especially for new developers. Hooks provide a more straightforward and functional approach to managing state, making components more concise and easier to maintain.
The useState Hook is used by importing it from the 'react' package:
import React, { useState } from 'react';
The useState Hook returns an array with two elements: the current state value and a function to update it. The syntax for using useState is as follows:
const [state, setState] = useState(initialState);
There are two primary ways to declare state in React:
In class components, state is declared within the component's constructor using ‘this.state’. Here's an example:
import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
message: 'Hello, World!'
};
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<p>Message: {this.state.message}</p>
</div>
);
}
}
export default MyComponent;
In this example, ‘this.state’ is used to declare an initial state object with count and message properties.
In functional components, useState in React class component can be declared using the useState Hook from React. Here is how you can declare state in a functional component:
import React, { useState } from 'react';
const MyComponent = () => {
const [count, setCount] = useState(0);
const [message, setMessage] = useState('Hello, World!');
return (
<div>
<p>Count: {count}</p>
<p>Message: {message}</p>
</div>
);
}
export default MyComponent;
In this example, useState is used to declare state variables count and message, along with their respective setter functions setCount and setMessage.
In both cases, the declared state variables (‘this.state’ in class components or variables returned by useState in functional components) can be accessed and modified within the component's render function, allowing the UI to update in response to changes in state.
Let us understand functional component with a simple useState in react example:
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
export default Counter;
In this example:
useState is not limited to managing simple primitive values like strings or numbers. It can also handle complex state, such as objects or arrays. Let us see an example:
import React, { useState } from 'react';
const Form = () => {
const [formData, setFormData] = useState({
username: '',
email: '',
password: ''
});
const handleInputChange = (e) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value
});
};
const handleSubmit = (e) => {
e.preventDefault();
console.log(formData); // Log form data
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="username"
placeholder="Username"
value={formData.username}
onChange={handleInputChange}
/>
<input
type="email"
name="email"
placeholder="Email"
value={formData.email}
onChange={handleInputChange}
/>
<input
type="password"
name="password"
placeholder="Password"
value={formData.password}
onChange={handleInputChange}
/>
<button type="submit">Submit</button>
</form>
);
};
export default Form;
In this example:
Sometimes, you may need to update the state based on its previous value. In such cases, you can pass a function to setState instead of an immediate value. This function receives the previous state as an argument. Let us see an example:
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
const increment = () => {
setCount(prevCount => prevCount + 1);
};
const decrement = () => {
setCount(prevCount => prevCount - 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};
export default Counter;
In this example, we define increment and decrement functions that update the count state based on its previous value.
Here is a react usestate object example:
Suppose, we want to build a simple form where users can enter their name and age. We will use useState to manage the state of the form data, which consists of an object with name and age properties.
import React, { useState } from 'react';
const Form = () => {
// Using useState to manage the form data state
const [formData, setFormData] = useState({ name: '', age: '' });
// Function to handle changes in form inputs
const handleChange = (e) => {
// Extracting the name and value from the input field
const { name, value } = e.target;
// Updating the formData state with the new value
setFormData({ ...formData, [name]: value });
};
// Function to handle form submission
const handleSubmit = (e) => {
e.preventDefault();
// Do something with the form data, for example, logging it
console.log(formData);
};
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Name:</label>
<input
type="text"
id="name"
name="name"
value={formData.name}
onChange={handleChange}
/>
</div>
<div>
<label htmlFor="age">Age:</label>
<input
type="text"
id="age"
name="age"
value={formData.age}
onChange={handleChange}
/>
</div>
<button type="submit">Submit</button>
</form>
);
};
export default Form;
In this example:
Here are some of the best practices to follow when using useState in React typescript to ensure clean and maintainable code:
Initialize state with the correct type: Make sure to provide the correct initial value when using useState. For example, if the state is a string, provide an empty string as the initial value.
Use state carefully: Avoid using state for everything. Do not use state if a value does not need to be managed within a component. Consider passing it down as props instead.
Update state immutably: When updating state in React that is an object or an array, always create a new copy of the state rather than mutating the original state directly. This ensures that React can properly detect changes and trigger re-renders.
Separate state concerns: If a component has multiple state variables, consider breaking them into separate useState calls. This makes the code easier to read and maintain.
Consider using useReducer for complex state logic: If your component's state logic becomes too complex, consider using the useReducer hook, which is suitable for managing state in such scenarios.
In this tutorial, we have explored the basics of using the useState in React for state management within functional components. We have covered its syntax, basic usage, handling complex state, and updating state based on the previous state. With useState, you can effectively manage state in your React applications, making them more concise and easier to maintain.
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.