TheuseStatehook is the fundamental building block for managing state in functional React components. It allows you to add state to functional components, which were previously only possible in class components.
What is State?
State represents data that can change over time and affects what is rendered on the screen. When state changes, React re-renders the component to reflect the updated data.
HowuseStateWorks
useStateis a function that takes an initial state value as an argument and returns an array with two elements:
- The current state value:The value of the state variable at the current moment.
- A state setter function:Used to update the state and trigger a re-render.
Basic Usage
import React, { useState } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default MyComponent;
Explanation:
import { useState } from 'react';– Imports theuseStatehook.const [count, setCount] = useState(0);count: The current state value.setCount: Function used to update the state.useState(0): Initializes state with0.
<p>You clicked {count} times</p>– Displays the current state value.<button onClick={() => setCount(count + 1)}>– Updates state and triggers a re-render.
Updating State
The state setter function is the only correct way to update state. Directly modifying the state variable willnottrigger a re-render.
Important Considerations:
- Immutability:
When updating objects or arrays, always create a new copy instead of modifying the existing one.
Example (Updating an object):
const [user, setUser] = useState({ name: 'John', age: 30 }); // Correct setUser({ ...user, age: 31 });Example (Updating an array):
const [items, setItems] = useState(['apple', 'banana']); // Correct setItems([...items, 'orange']); - Functional Updates:
Use a functional update when the new state depends on the previous state.
const [count, setCount] = useState(0); setCount(prevCount => prevCount + 1);This ensures you always work with the most recent state value.
Multiple State Variables
You can calluseStatemultiple times within a single component.
import React, { useState } from 'react';
function MyForm() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
return (
<div>
<label>Name:</label>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<label>Email:</label>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<p>Name: {name}</p>
<p>Email: {email}</p>
</div>
);
}
export default MyForm;
Here,nameandemailare managed independently using separateuseStatehooks.
Summary
useStateadds state to functional components.- It returns the current state and a setter function.
- Always update state using the setter function.
- Maintain immutability for objects and arrays.
- Use functional updates when state depends on previous values.
- Multiple
useStatehooks can exist in one component.