Lab06 ReactHooks
Lab06 ReactHooks
Objective: Utilize the useEffect hook to manage side effects in a React functional
component.
Task:
1. Set Up the Project: Initialize a new React project using Create React App, Vite, or
any preferred setup. Ensure all necessary dependencies are installed.
2. Create a Component with Local State: Develop a functional component named
UserList. Within this component, use the useState hook to create a state variable
users, initialized as an empty array.
3. Fetch Data Using useEffect: Implement the useEffect hook to fetch user data
from a public API (e.g., JSONPlaceholder) when the component mounts. Update the
users state with the fetched data.
4. Display the Fetched Data: Render the list of users in the component, displaying
relevant information such as name and email.
Solution:
function UserList() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => response.json())
.then((data) => setUsers(data));
}, []);
return (
<div>
<h2>User List</h2>
<ul>
{users.map((user) => (
<li key={user.id}>{user.name} ({user.email})</li>
))}
</ul>
</div>
);
}
function DataFetcher() {
const [query, setQuery] = useState('react');
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
if (!query) return;
fetchData();
}, [query]); // Dependency array includes 'query'
return (
<div>
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Enter search term"
/>
{loading && <p>Loading...</p>}
{error && <p>Error: {error}</p>}
<ul>
{data.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}
Objective: Use the useContext hook to manage and consume global state across multiple
components.
Task:
Solution:
jsx
CopyEdit
import React, { useState, useContext } from 'react';
function ThemedButton() {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
<button
style={{
backgroundColor: theme === 'light' ? '#fff' : '#333',
color: theme === 'light' ? '#000' : '#fff',
}}
onClick={toggleTheme}
>
Toggle Theme
</button>
);
}
function App() {
return (
<ThemeProvider>
<ThemedButton />
</ThemeProvider>
);
}