useState Example-1
useState Example-1
function Counter() {
const [count, setCount] = useState(0); // Initialize state with 0
return (
<div>
<h1>Count: {count}</h1>
<button onClick={increment}>Increment</button>
</div>
);
}
2) Bulb ON/OFF
function Lightbulb() {
const [isOn, setIsOn] = useState(false); // Initial state is 'off'
return (
<div>
<h1>The light is {isOn ? "ON" : "OFF"}</h1>
<button onClick={toggleLight}>
{isOn ? "Turn Off" : "Turn On"}
</button>
</div>
);
}
3] useEffect Example
function UserList() {
const [users, setUsers] = useState([]); // State to store fetched data
const [loading, setLoading] = useState(true); // State to show a loading
indicator
useEffect(() => {
// Fetch data from the API
fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => response.json()) // Convert response to JSON
.then((data) => {
setUsers(data); // Update users state with the fetched data
setLoading(false); // Set loading to false after data is fetched
})
.catch((error) => console.error('Error fetching data:', error));
}, []); // Empty dependency array means this effect runs only once
return (
<div>
<h1>User List</h1>
{loading ? (
<p>Loading...</p> // Show loading message while fetching
) : (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li> // Render user names
))}
</ul>
)}
</div>
);
}
4) Random Joke
function RandomJoke() {
const [joke, setJoke] = useState('');
const [loading, setLoading] = useState(false);
return (
<div>
<h1>Random Joke</h1>
<button onClick={fetchJoke}>Get a Joke</button>
{loading ? <p>Loading...</p> : <p>{joke}</p>}
</div>
);
}