In React, useState
is a fundamental hook that allows you to add state to functional components. State in React is a way to store and manage data that changes over time, such as user inputs, component visibility, or dynamic content. The useState
hook provides a simple way to track these changes and update the UI accordingly.
useState
The useState
hook is used to declare a state variable in a functional component. It returns an array with two elements: the current state value and a function to update that state.
1. Importing useState
:
To use useState
, you must first import it from React:
import React, { useState } from 'react';
2. Declaring State:
Use the useState
function to declare a state variable. Pass the initial state value as an argument to useState
.
const [state, setState] = useState(initialValue);
state
: The current state value.
setState
: The function used to update the state.
initialValue
: The initial value of the state (can be any data type).
Example:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // Declaring a state variable 'count'
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default Counter;
In this example, count
is a state variable initialized to 0
. The setCount
function updates the count
value whenever the button is clicked.
useState
State updates in React using useState
are asynchronous and cause the component to re-render with the new state value. You can update the state by calling the state setter function (setState
) and passing the new value.
3. Updating State Based on Previous State:
If the new state depends on the previous state, use a function inside setState
to ensure accurate updates.
setCount(prevCount => prevCount + 1);
Example:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(prevCount => prevCount + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
export default Counter;
This approach is especially useful in cases where multiple state updates might be queued, ensuring that each update uses the most recent state.
When managing more complex state (such as objects or arrays), useState
can still be used effectively. However, you need to update the state immutably to avoid unintended side effects.
4. Updating Object State:
When the state is an object, use the spread operator to update specific properties without mutating the original object.
setState(prevState => ({
...prevState,
key: newValue
}));
Example:
import React, { useState } from 'react';
function UserProfile() {
const [user, setUser] = useState({ name: '', age: 0 });
const updateName = (newName) => {
setUser(prevUser => ({
...prevUser,
name: newName
}));
};
return (
<div>
<p>Name: {user.name}</p>
<p>Age: {user.age}</p>
<button onClick={() => updateName('John')}>Set Name</button>
</div>
);
}
export default UserProfile;
useState
in React
import React, { useState } from 'react';
function LoginForm() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = (event) => {
event.preventDefault();
// Handle form submission
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Username"
/>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Password"
/>
<button type="submit">Login</button>
</form>
);
}
export default LoginForm;
import React, { useState } from 'react';
function ToggleComponent() {
const [isVisible, setIsVisible] = useState(true);
return (
<div>
<button onClick={() => setIsVisible(!isVisible)}>
{isVisible ? 'Hide' : 'Show'} Content
</button>
{isVisible && <p>This is the content to toggle.</p>}
</div>
);
}
export default ToggleComponent;
The useState
hook is a powerful and essential tool in React for managing state within functional components. By understanding and effectively using useState
, you can build dynamic and interactive user interfaces with ease.
Jorge García
Fullstack developer