0% found this document useful (0 votes)
2 views

useState Example-1

The document contains four React components: a Counter that increments a number, a Lightbulb that toggles its on/off state, a UserList that fetches and displays user data from an API, and a RandomJoke that retrieves and displays a random joke. Each component utilizes React's useState and useEffect hooks to manage state and side effects. The examples demonstrate basic interactivity and data fetching in React applications.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

useState Example-1

The document contains four React components: a Counter that increments a number, a Lightbulb that toggles its on/off state, a UserList that fetches and displays user data from an API, and a RandomJoke that retrieves and displays a random joke. Each component utilizes React's useState and useEffect hooks to manage state and side effects. The examples demonstrate basic interactivity and data fetching in React applications.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

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;

You might also like