1) Counter App
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // Initialize state with 0
const increment = () => {
setCount(count + 1); // Update state
};
return (
<div>
<h1>Count: {count}</h1>
<button onClick={increment}>Increment</button>
</div>
);
}
export default Counter;
2) Bulb ON/OFF
import { useState } from 'react';
function Lightbulb() {
const [isOn, setIsOn] = useState(false); // Initial state is 'off'
const toggleLight = () => {
setIsOn(!isOn); // Toggle between true and false
};
return (
<div>
<h1>The light is {isOn ? "ON" : "OFF"}</h1>
<button onClick={toggleLight}>
{isOn ? "Turn Off" : "Turn On"}
</button>
</div>
);
}
export default Lightbulb;
3] useEffect Example
import React, { useState, useEffect } from 'react';
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>
);
}
export default UserList;
4) Random Joke
import React, { useState } from 'react';
function RandomJoke() {
const [joke, setJoke] = useState('');
const [loading, setLoading] = useState(false);
const fetchJoke = () => {
setLoading(true);
fetch('https://official-joke-api.appspot.com/random_joke')
.then((response) => response.json())
.then((data) => {
setJoke(`${data.setup} - ${data.punchline}`); // Update joke state
setLoading(false);
})
.catch((error) => {
console.error('Error fetching joke:', error);
setLoading(false);
});
};
return (
<div>
<h1>Random Joke</h1>
<button onClick={fetchJoke}>Get a Joke</button>
{loading ? <p>Loading...</p> : <p>{joke}</p>}
</div>
);
}
export default RandomJoke;