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
React
anduseState
from the ‘react’ package. - We define a functional component called
Counter
. - Inside the component, we use the
useState
hook to create a state variablecount
with an initial value of0
. - We define two event handlers,
increment
anddecrement
, which update thecount
state using thesetCount
function 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
increment
anddecrement
functions 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
React
anduseState
from the ‘react’ package. - We define a functional component called
NameUpdater
. - Inside the component, we use the
useState
hook to create a state variablename
with an initial value of"John"
. - We define an event handler called
updateName
that updates thename
state using thesetName
function, changing it to"Alice"
. - In the component’s JSX, we display the current
name
value and provide a button that triggers theupdateName
function 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
React
anduseState
from the ‘react’ package. - We define a functional component called
ToggleButton
. - Inside the component, we use the
useState
hook to create a boolean state variableisToggled
with an initial value offalse
. - We define an event handler called
toggle
that updates theisToggled
state using thesetIsToggled
function, toggling it betweentrue
andfalse
. - In the component’s JSX, we display the current toggle status, and we provide a button that triggers the
toggle
function 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
React
anduseState
from the ‘react’ package. - We define a functional component called
UserProfile
. - Inside the component, we use the
useState
hook to create a state variableuser
with an initial object value containing properties likefirstName
,lastName
, andage
. - We define an event handler called
increaseAge
that updates theage
property of theuser
state object by creating a new object with the spread operator (...user
) and modifying theage
property. - In the component’s JSX, we display various properties of the
user
object, including the first name, last name, and age. We also provide a button that triggers theincreaseAge
function 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
React
anduseState
from the ‘react’ package. - We define a functional component called
TodoList
. - Inside the component, we use the
useState
hook to create a state variabletodos
with an initial empty array. - We define two event handlers:
addTodo
to add a new todo to thetodos
array andcompleteTodo
to mark a todo as completed. - In the
addTodo
function, we create a new todo object and add it to thetodos
array by creating a new array with the spread operator. - In the
completeTodo
function, we update thecompleted
property of a todo at a specific index and then update thetodos
array. - In the component’s JSX, we map over the
todos
array 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
addTodo
function 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
React
anduseState
from the ‘react’ package. - We define a functional component called
Counter
. - Inside the component, we use the
useState
hook to create a state variablecount
with an initial value of0
. - We define two event handlers:
increment
anddecrement
. Instead of directly updatingcount
, these functions use the functional form ofsetCount
by 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
count
value, and we provide buttons that trigger theincrement
anddecrement
functions 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
React
anduseState
from the ‘react’ package. - We define a functional component called
UserProfile
. - Inside the component, we use the
useState
hook to create a boolean state variableisLoggedIn
with an initial value offalse
. - We define an event handler called
toggleLogin
that toggles theisLoggedIn
state betweentrue
andfalse
. - In the component’s JSX, we conditionally render different content based on the
isLoggedIn
state. 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
toggleLogin
function, which changes theisLoggedIn
state, 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
React
anduseState
from the ‘react’ package. - We define a functional component called
FormInput
. - Inside the component, we use the
useState
hook to create a state variableinputValue
with an initial value of an empty string. - We define two event handlers:
handleInputChange
is used to update theinputValue
state whenever the input field value changes.handleSubmit
is 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
value
is set to theinputValue
state, and theonChange
event is set to thehandleInputChange
function to keep the state synchronized with the input value. - Below the form, we display the entered value by rendering the
inputValue
state.
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
React
anduseState
from the ‘react’ package. - We define a functional component called
FormInput
. - Inside the component, we use the
useState
hook to create a state variableinputValue
with an initial value of an empty string. - We define two event handlers:
handleInputChange
is used to update theinputValue
state whenever the input field value changes.handleSubmit
is 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
value
is set to theinputValue
state, and theonChange
event is set to thehandleInputChange
function to keep the state synchronized with the input value. - Below the form, we display the entered value by rendering the
inputValue
state.
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
React
anduseState
from the ‘react’ package. - We define a functional component called
UserProfile
. - Inside the component, we use the
useState
hook to create two state variables,firstName
andlastName
, with initial values of empty strings. - We define two event handlers:
handleFirstNameChange
andhandleLastNameChange
, which update thefirstName
andlastName
states, 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
value
of each input field is set to the corresponding state variable (firstName
orlastName
), and theonChange
event is set to the respective event handlers. - We also display the full name by rendering the
firstName
andlastName
state 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 ase
for brevity.e.target
refers to the DOM element that triggered the event. In this context, it represents the specific<input>
element where the user is typing.e.target.value
is 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.value
will contain the text that the user has entered.
So, in the handleFirstNameChange
function:
(e)
is the event object.e.target
is the<input>
element where the user is typing.e.target.value
is the current value of that input field, which is being used to update thefirstName
state 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
, anduseEffect
from the ‘react’ package. - We define a functional component called
DataFetching
. - Inside the component, we use the
useState
hook to create three state variables:data
to store the fetched data.loading
to track whether data is being fetched (initially set totrue
).error
to handle any potential errors (initially set tonull
).
- We use the
useEffect
hook to fetch data from an API when the component mounts. We define the API URL (apiUrl
) and use thefetch
function 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
error
state. - If the response is okay, we parse the JSON response and set the
data
state 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
. Ifloading
istrue
, 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.