The useState hook in React is used to manage state in functional components. Here are 20 usage examples to illustrate how it can be used:
Example of using the useState hook for basic state management in a React functional component:
import React, { useState } from 'react';
function Counter() {
// Define a state variable 'count' with an initial value of 0
const [count, setCount] = useState(0);
// Event handler to increment the count
const increment = () => {
setCount(count + 1);
};
// Event handler to decrement the count
const decrement = () => {
setCount(count - 1);
};
return (
<div>
<h1>Counter App</h1>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
export default Counter;
In this example:
- We import
ReactanduseStatefrom the ‘react’ package. - We define a functional component called
Counter. - Inside the component, we use the
useStatehook to create a state variablecountwith an initial value of0. - We define two event handlers,
incrementanddecrement, which update thecountstate using thesetCountfunction with the current value plus or minus one, respectively. - In the component’s JSX, we display the current count value and provide buttons that trigger the
incrementanddecrementfunctions when clicked.
This example demonstrates a basic counter application where the count state is managed using the useState hook, and the UI updates accordingly when the state changes.
Example of using the useState hook to update state in a React functional component:
import React, { useState } from 'react';
function NameUpdater() {
// Define a state variable 'name' with an initial value of "John"
const [name, setName] = useState("John");
// Event handler to update the name
const updateName = () => {
setName("Alice");
};
return (
<div>
<h1>Name Updater</h1>
<p>Name: {name}</p>
<button onClick={updateName}>Update Name</button>
</div>
);
}
export default NameUpdater;
In this example:
- We import
ReactanduseStatefrom the ‘react’ package. - We define a functional component called
NameUpdater. - Inside the component, we use the
useStatehook to create a state variablenamewith an initial value of"John". - We define an event handler called
updateNamethat updates thenamestate using thesetNamefunction, changing it to"Alice". - In the component’s JSX, we display the current
namevalue and provide a button that triggers theupdateNamefunction when clicked.
This example demonstrates how to update the state using the useState hook, and the UI reflects the updated state value when the button is clicked, changing the name from “John” to “Alice.”
Example of using the useState hook to toggle a boolean state in a React functional component:
import React, { useState } from 'react';
function ToggleButton() {
// Define a boolean state variable 'isToggled' with an initial value of 'false'
const [isToggled, setIsToggled] = useState(false);
// Event handler to toggle the boolean state
const toggle = () => {
setIsToggled(!isToggled); // Toggle the state
};
return (
<div>
<h1>Toggle Button</h1>
<p>Toggle Status: {isToggled ? 'On' : 'Off'}</p>
<button onClick={toggle}>Toggle</button>
</div>
);
}
export default ToggleButton;
In this example:
- We import
ReactanduseStatefrom the ‘react’ package. - We define a functional component called
ToggleButton. - Inside the component, we use the
useStatehook to create a boolean state variableisToggledwith an initial value offalse. - We define an event handler called
togglethat updates theisToggledstate using thesetIsToggledfunction, toggling it betweentrueandfalse. - In the component’s JSX, we display the current toggle status, and we provide a button that triggers the
togglefunction when clicked.
This example demonstrates how to toggle a boolean state using the useState hook, and the UI reflects the state changes when the “Toggle” button is clicked, switching between “On” and “Off” statuses.
Example of using the useState hook to manage state with objects in a React functional component:
import React, { useState } from 'react';
function UserProfile() {
// Define a state variable 'user' with an initial object value
const [user, setUser] = useState({
firstName: 'John',
lastName: 'Doe',
age: 30,
});
// Event handler to update the user's age
const increaseAge = () => {
setUser({ ...user, age: user.age + 1 }); // Update age property
};
return (
<div>
<h1>User Profile</h1>
<p>First Name: {user.firstName}</p>
<p>Last Name: {user.lastName}</p>
<p>Age: {user.age}</p>
<button onClick={increaseAge}>Increase Age</button>
</div>
);
}
export default UserProfile;
In this example:
- We import
ReactanduseStatefrom the ‘react’ package. - We define a functional component called
UserProfile. - Inside the component, we use the
useStatehook to create a state variableuserwith an initial object value containing properties likefirstName,lastName, andage. - We define an event handler called
increaseAgethat updates theageproperty of theuserstate object by creating a new object with the spread operator (...user) and modifying theageproperty. - In the component’s JSX, we display various properties of the
userobject, including the first name, last name, and age. We also provide a button that triggers theincreaseAgefunction when clicked.
This example demonstrates how to manage state with objects using the useState hook, and the UI reflects the updated age property when the “Increase Age” button is clicked.
Example of using the useState hook to manage state with arrays in a React functional component:
import React, { useState } from 'react';
function TodoList() {
// Define a state variable 'todos' with an initial empty array
const [todos, setTodos] = useState([]);
// Event handler to add a new todo
const addTodo = () => {
const newTodo = { text: 'New Task', completed: false };
setTodos([...todos, newTodo]); // Add the new todo to the array
};
// Event handler to mark a todo as completed
const completeTodo = (index) => {
const updatedTodos = [...todos];
updatedTodos[index].completed = true;
setTodos(updatedTodos); // Update the array with the completed todo
};
return (
<div>
<h1>Todo List</h1>
<ul>
{todos.map((todo, index) => (
<li key={index} style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}>
{todo.text}
{!todo.completed && (
<button onClick={() => completeTodo(index)}>Complete</button>
)}
</li>
))}
</ul>
<button onClick={addTodo}>Add Todo</button>
</div>
);
}
export default TodoList;
In this example:
- We import
ReactanduseStatefrom the ‘react’ package. - We define a functional component called
TodoList. - Inside the component, we use the
useStatehook to create a state variabletodoswith an initial empty array. - We define two event handlers:
addTodoto add a new todo to thetodosarray andcompleteTodoto mark a todo as completed. - In the
addTodofunction, we create a new todo object and add it to thetodosarray by creating a new array with the spread operator. - In the
completeTodofunction, we update thecompletedproperty of a todo at a specific index and then update thetodosarray. - In the component’s JSX, we map over the
todosarray and display each todo as a list item. Completed todos have a line-through style, and there’s a “Complete” button for uncompleted todos. - We provide a button that triggers the
addTodofunction when clicked, adding a new todo to the list.
This example demonstrates how to manage state with arrays using the useState hook in a simple todo list application.
Example of using the useState hook with a function to update state in a React functional component:
import React, { useState } from 'react';
function Counter() {
// Define a state variable 'count' with an initial value of 0
const [count, setCount] = useState(0);
// Event handler to increment the count
const increment = () => {
setCount((prevCount) => prevCount + 1);
};
// Event handler to decrement the count
const decrement = () => {
setCount((prevCount) => prevCount - 1);
};
return (
<div>
<h1>Counter App</h1>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
export default Counter;
In this example:
- We import
ReactanduseStatefrom the ‘react’ package. - We define a functional component called
Counter. - Inside the component, we use the
useStatehook to create a state variablecountwith an initial value of0. - We define two event handlers:
incrementanddecrement. Instead of directly updatingcount, these functions use the functional form ofsetCountby passing a function that takes the previous state (prevCount) and returns the new state by incrementing or decrementing it. - In the component’s JSX, we display the current
countvalue, and we provide buttons that trigger theincrementanddecrementfunctions when clicked.
This example demonstrates how to update state using a function with the useState hook, ensuring that the state changes are based on the previous state value.
Example of using the useState hook for conditional rendering in a React functional component:
import React, { useState } from 'react';
function UserProfile() {
// Define a state variable 'isLoggedIn' with an initial value of 'false'
const [isLoggedIn, setIsLoggedIn] = useState(false);
// Event handler to toggle the login status
const toggleLogin = () => {
setIsLoggedIn(!isLoggedIn);
};
return (
<div>
<h1>User Profile</h1>
{isLoggedIn ? (
<>
<p>Welcome, User!</p>
<button onClick={toggleLogin}>Logout</button>
</>
) : (
<>
<p>Please log in to access your profile.</p>
<button onClick={toggleLogin}>Login</button>
</>
)}
</div>
);
}
export default UserProfile;
In this example:
- We import
ReactanduseStatefrom the ‘react’ package. - We define a functional component called
UserProfile. - Inside the component, we use the
useStatehook to create a boolean state variableisLoggedInwith an initial value offalse. - We define an event handler called
toggleLoginthat toggles theisLoggedInstate betweentrueandfalse. - In the component’s JSX, we conditionally render different content based on the
isLoggedInstate. If the user is logged in, we display a welcome message and a “Logout” button. If the user is not logged in, we display a message prompting them to log in and a “Login” button. - Clicking the “Login” or “Logout” button triggers the
toggleLoginfunction, which changes theisLoggedInstate, and the content is updated accordingly.
This example demonstrates how to use the useState hook for conditional rendering in a simple user profile component that toggles between login and logout states.
Example of using the useState hook to manage form input in a React functional component:
import React, { useState } from 'react';
function FormInput() {
// Define a state variable 'inputValue' with an initial value of an empty string
const [inputValue, setInputValue] = useState('');
// Event handler to update the inputValue state
const handleInputChange = (e) => {
setInputValue(e.target.value);
};
// Event handler to handle form submission
const handleSubmit = (e) => {
e.preventDefault();
alert('Form submitted with value: ' + inputValue);
};
return (
<div>
<h1>Form Input Example</h1>
<form onSubmit={handleSubmit}>
<label>
Enter something:
<input
type="text"
value={inputValue}
onChange={handleInputChange}
/>
</label>
<button type="submit">Submit</button>
</form>
<p>You entered: {inputValue}</p>
</div>
);
}
export default FormInput;
In this example:
- We import
ReactanduseStatefrom the ‘react’ package. - We define a functional component called
FormInput. - Inside the component, we use the
useStatehook to create a state variableinputValuewith an initial value of an empty string. - We define two event handlers:
handleInputChangeis used to update theinputValuestate whenever the input field value changes.handleSubmitis used to handle the form submission. It prevents the default form submission behavior and alerts the entered value.
- In the component’s JSX, we render a form with an input field and a submit button. The input field’s
valueis set to theinputValuestate, and theonChangeevent is set to thehandleInputChangefunction to keep the state synchronized with the input value. - Below the form, we display the entered value by rendering the
inputValuestate.
This example demonstrates how to use the useState hook to manage form input in a React component. When the user types in the input field and submits the form, the entered value is displayed below the form.
Example of using the useState hook to manage form input in a React functional component:
import React, { useState } from 'react';
function FormInput() {
// Define a state variable 'inputValue' with an initial value of an empty string
const [inputValue, setInputValue] = useState('');
// Event handler to update the inputValue state
const handleInputChange = (e) => {
setInputValue(e.target.value);
};
// Event handler to handle form submission
const handleSubmit = (e) => {
e.preventDefault();
alert('Form submitted with value: ' + inputValue);
};
return (
<div>
<h1>Form Input Example</h1>
<form onSubmit={handleSubmit}>
<label>
Enter something:
<input
type="text"
value={inputValue}
onChange={handleInputChange}
/>
</label>
<button type="submit">Submit</button>
</form>
<p>You entered: {inputValue}</p>
</div>
);
}
export default FormInput;
In this example:
- We import
ReactanduseStatefrom the ‘react’ package. - We define a functional component called
FormInput. - Inside the component, we use the
useStatehook to create a state variableinputValuewith an initial value of an empty string. - We define two event handlers:
handleInputChangeis used to update theinputValuestate whenever the input field value changes.handleSubmitis used to handle the form submission. It prevents the default form submission behavior and alerts the entered value.
- In the component’s JSX, we render a form with an input field and a submit button. The input field’s
valueis set to theinputValuestate, and theonChangeevent is set to thehandleInputChangefunction to keep the state synchronized with the input value. - Below the form, we display the entered value by rendering the
inputValuestate.
This example demonstrates how to use the useState hook to manage form input in a React component. When the user types in the input field and submits the form, the entered value is displayed below the form.
Example of managing multiple states using the useState hook in a React functional component:
import React, { useState } from 'react';
function UserProfile() {
// Define state variables for first name and last name with initial values
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
// Event handler to update the first name
const handleFirstNameChange = (e) => {
setFirstName(e.target.value);
};
// Event handler to update the last name
const handleLastNameChange = (e) => {
setLastName(e.target.value);
};
return (
<div>
<h1>User Profile</h1>
<label>
First Name:
<input
type="text"
value={firstName}
onChange={handleFirstNameChange}
/>
</label>
<br />
<label>
Last Name:
<input
type="text"
value={lastName}
onChange={handleLastNameChange}
/>
</label>
<br />
<p>Full Name: {firstName} {lastName}</p>
</div>
);
}
export default UserProfile;
In this example:
- We import
ReactanduseStatefrom the ‘react’ package. - We define a functional component called
UserProfile. - Inside the component, we use the
useStatehook to create two state variables,firstNameandlastName, with initial values of empty strings. - We define two event handlers:
handleFirstNameChangeandhandleLastNameChange, which update thefirstNameandlastNamestates, respectively, based on the value entered in the input fields. - In the component’s JSX, we render two input fields for the first name and last name. The
valueof each input field is set to the corresponding state variable (firstNameorlastName), and theonChangeevent is set to the respective event handlers. - We also display the full name by rendering the
firstNameandlastNamestate variables.
This example demonstrates how to manage multiple states (in this case, first name and last name) using the useState hook in a React component. When the user enters values in the input fields, the state variables are updated, and the full name is displayed dynamically.
Also
// Event handler to update the first name
const handleFirstNameChange = (e) => {
setFirstName(e.target.value);
};
Here’s an explanation of what (e) and e.target.value represent:
(e)is a commonly used abbreviation for an event object. It’s a parameter that represents the event that occurred, in this case, the “change” event that happens when a user types into an input field. The(e)parameter is a convention, and you can name it whatever you like, but it’s commonly referred to asefor brevity.e.targetrefers to the DOM element that triggered the event. In this context, it represents the specific<input>element where the user is typing.e.target.valueis a property of the DOM element (in this case, the input field) that contains the current value of the input. When the user types into the input field,e.target.valuewill contain the text that the user has entered.
So, in the handleFirstNameChange function:
(e)is the event object.e.targetis the<input>element where the user is typing.e.target.valueis the current value of that input field, which is being used to update thefirstNamestate variable usingsetFirstName(e.target.value).
In summary, when the user types into the input field, the handleFirstNameChange function is called with the event object (e), and it updates the firstName state with the current value of the input field, making the component’s state reflect the user’s input.
Example of using the useState hook to fetch data from an API in a React functional component:
import React, { useState, useEffect } from 'react';
function DataFetching() {
// Define a state variable 'data' to store the fetched data
const [data, setData] = useState(null);
// Define a state variable 'loading' to track whether data is being fetched
const [loading, setLoading] = useState(true);
// Define a state variable 'error' to handle any potential errors
const [error, setError] = useState(null);
// Use the useEffect hook to fetch data from an API when the component mounts
useEffect(() => {
// Define the API URL you want to fetch data from
const apiUrl = 'https://jsonplaceholder.typicode.com/posts/1';
// Fetch data from the API
fetch(apiUrl)
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then((data) => {
setData(data);
setLoading(false); // Set loading to false when data is successfully fetched
})
.catch((error) => {
setError(error);
setLoading(false); // Set loading to false in case of an error
});
}, []); // Empty dependency array means this effect runs once when the component mounts
return (
<div>
<h1>Data Fetching Example</h1>
{loading ? (
<p>Loading...</p>
) : error ? (
<p>Error: {error.message}</p>
) : (
<div>
<h2>Title: {data.title}</h2>
<p>Body: {data.body}</p>
</div>
)}
</div>
);
}
export default DataFetching;
In this example:
- We import
React,useState, anduseEffectfrom the ‘react’ package. - We define a functional component called
DataFetching. - Inside the component, we use the
useStatehook to create three state variables:datato store the fetched data.loadingto track whether data is being fetched (initially set totrue).errorto handle any potential errors (initially set tonull).
- We use the
useEffecthook to fetch data from an API when the component mounts. We define the API URL (apiUrl) and use thefetchfunction to make a GET request. - We handle the fetch response and update the state variables accordingly:
- If the response is not okay (e.g., a network error), we set the
errorstate. - If the response is okay, we parse the JSON response and set the
datastate with the fetched data.
- If the response is not okay (e.g., a network error), we set the
- We render the component based on the current state of
loading,error, anddata. Ifloadingistrue, we display a loading message. If there’s an error, we display the error message. If data has been fetched successfully, we display the data.
This example demonstrates how to use the useState and useEffect hooks to fetch and display data from an API in a React component.







