useState Hook
The useState hook is a fundamental concept in React, allowing you to manage state in functional components. Introduced in React 16.8, it provides a simple way to add state to your components. In this section, we’ll explore how to use the useState hook in React 19, along with best practices and examples.
Basic Example
Let’s start with a basic example of using the useState hook. In this example, we’ll create a simple counter that increments when a button is clicked.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}In this example, we import the useState hook from React and create a new state variable count with an initial value of 0. We also create a setCount function to update the state. When the button is clicked, the setCount function is called, updating the state and triggering a re-render of the component.
Advanced Usage
Let’s consider a more complex example where we need to manage multiple state variables. In this case, we can use the useState hook multiple times or use an object to store our state.
import { useState } from 'react';
function UserForm() {
const [username, setUsername] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = (event) => {
event.preventDefault();
console.log({ username, email, password });
};
return (
<form onSubmit={handleSubmit}>
<label>
Username:
<input type="text" value={username} onChange={(event) => setUsername(event.target.value)} />
</label>
<label>
Email:
<input type="email" value={email} onChange={(event) => setEmail(event.target.value)} />
</label>
<label>
Password:
<input type="password" value={password} onChange={(event) => setPassword(event.target.value)} />
</label>
<button type="submit">Submit</button>
</form>
);
}In this example, we use the useState hook three times to manage the username, email, and password state variables. We also create a handleSubmit function to handle the form submission.
Best Practices
Here are some best practices to keep in mind when using the useState hook:
- Use the
useStatehook only in functional components. - Avoid using the
useStatehook inside loops or conditional statements. - Use the
useStatehook with an initial value to avoid undefined state. - Use the
useCallbackhook to memoize functions that depend on state variables.
Key Takeaways
Here are the key takeaways from this section:
- The
useStatehook is used to manage state in functional components. - The
useStatehook returns an array with two elements: the state variable and the update function. - Use the
useStatehook with an initial value to avoid undefined state. - Avoid using the
useStatehook inside loops or conditional statements.