State is a specific piece of data that a component manages. It can change over time, triggering the component to re-render with the updated state. This allows your UI to respond to user actions and data changes.
React provides the "useState" hook for managing state within functional components. This hook allows you to declare and manipulate state variables within a component.
Here's how to use "useState":
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // Declare state variable "count" with initial value 0
const handleClick = () =>; {
setCount(count + 1); // Update state using the setCount function
};
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handleClick}>Click me</button>
</div>
);
}
In this example:
You can use the state value to conditionally render different UI elements based on the component's state. This allows for dynamic and interactive behavior.
function Login() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const handleLogin = () => {
setIsLoggedIn(true);
};
return (
<div>
{isLoggedIn ? ( // Conditional rendering based on state
<p>Welcome, you are logged in!</p>
) : (
<button onClick={handleLogin}>Login</button>
)}
</div>
);
}
This example demonstrates how to conditionally render content based on the "isLoggedIn" state. We'll explore more advanced state management techniques and concepts in the following chapters. Stay tuned!
Next page: Handling Events