useEffect in React
● useEffect is a React Hook for handling side effects in functional components.
● It runs after the component renders.
● Common use cases:
○ Fetching data from APIs
○ Updating the DOM
○ Managing subscriptions
○ Handling event listeners.
Slide 2: Why Use useEffect?
● Handles side effects in functional components.
● Replaces class component lifecycle methods:
○ componentDidMount
○ componentDidUpdate
○ componentWillUnmount
● Helps manage API calls, event listeners, and local storage.
Fetching and Displaying Users
This React component, UserList, fetches a list of users from an API and displays them.
Importing Required Modules
import React, { useState, useEffect } from "react";
import React → Imports React to create a component.
useState → A React Hook that allows us to store and manage component data (users list).
useEffect → A React Hook that performs side effects (like fetching data from an API).
Example:
Think of useState as a notebook where you store information (like a student list).
useEffect is like asking an assistant to fetch the list from the database when the page
loads.
Creating the UserList Declaring State for Users
Component const [users, setUsers] = useState([]);
function UserList() {
● users → Stores the user list (initially
● Declares a functional component empty []).
named UserList. ● setUsers → Updates users with API
data.
Real-life Example:
Real-life Example:
● A teacher preparing to call roll numbers
in class. ● users = An empty attendance register.
● setUsers = Filling the register as
students arrive.
Fetching Data from API (useEffect)
useEffect(function () {
fetch("https://jsonplaceholder.typicode.com/users")
.then(function (response) { return response.json(); })
.then(function (data) { setUsers(data); });
}, [ ]);
● useEffect runs once (empty [] dependency array).
● fetch(url) requests data from an API.
● .then(response.json()) converts API response to JSON.
● .then(data => setUsers(data)) updates state with the
received data.
Example:
● Opening a WhatsApp group and seeing the list of members
fetched from the server.
Displaying the Users List
return (
<div>
<h2>Users List</h2>
<ul>
{users.map(function (user) {
return <li key={user.id}>{user.name}</li>;
})}
</ul>
</div>
);
● Loops through users with .map() to display names in <li>
elements.
● Calling out student names from a class list.
Understanding map() Function A teacher calling out each student's
users.map(function (user) { return <li name in a classroom.
key={user.id}>{user.name}</li>; }); Given Data:
Explanation: [
{ id: 1, name: "Amit" },
● map() iterates over users. { id: 2, name: "Rohit" },
● function(user) { ... } → { id: 3, name: "Sneha" }
Defines a function that runs for each ]
user.
Rendered Output:
● user.name → Extracts the user’s
name. <li>Amit</li>
<li>Rohit</li>
<li>Sneha</li>
Why Use key={user.id}? Exporting the Component
<li key={user.id}>{user.name}</li> export default UserList;
● React requires unique key props ● Makes the component available
for list items. for use in other files.
● key={user.id} prevents React
Real-life Example:
from re-rendering all items
unnecessarily. ● Writing a report and submitting it
to the principal for review.
Real-life Example:
● A classroom attendance sheet
where each student has a unique
roll number.
“Imagine opening your Facebook
Friends List. The app fetches your
friends from the server and displays
them.
Introduction to React Router
● React Router is a popular library for handling
navigation in React applications.
● It allows us to create Single Page Applications (SPAs)
with multiple views.
● It provides dynamic routing capabilities with URL
parameters.
E-commerce Website Navigation
In an online shopping platform, users navigate through different sections
and product details using nested routes.
Example Routes in an E-commerce App
1. /shop → Shows all product categories.
2. /shop/electronics → Lists all electronic items.
3. /shop/electronics/laptops → Shows only laptops.
4. /shop/electronics/laptops/:id → Shows details of a specific
laptop.
5. /shop/cart → Shopping cart page.
6. /shop/orders → User's order history.
Installing React Router
Title: Installing React Router Code Snippet:
npm install react-router-dom
Content:
● Install react-router-dom package to
use React Router.
● It provides components like
BrowserRouter, Route, Link, and
Outlet.
●
Code Implementation
Step 1: Set Up Routes Using createBrowserRouter
import React from "react";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import Job from "./pages/job";
import JobDetails from "./components/JobDetails";
const router = createBrowserRouter([
{
path: "/job",
element: <Job />, // Parent Route
children: [
{ path: "post/:id", element: <jobDetails /> }, // Nested Route
],
},
]);
function App() {
return <RouterProvider router={router} />; /job → Loads Job.js (Parent Page).
}
export default App; /job/post/:id → Loads
jobDetails.js dynamically when a
post is clicked.
import React from "react";
import { Outlet } from "react-router-dom";
import JobList from "../components/JobList";
function Job() {
return (
<div>
<h1>Job Posts</h1>
<JobList />
<Outlet /> {/* Renders nested routes (PostDetails) */}
</div>
);
}
export default Job;
Create BlogList.js (List of Blog Posts)
import React from "react";
import { Link } from "react-router-dom";
const posts = [
{ id: 1, title: "Java Devloper" },
{ id: 2, title: "MERN Devloper" },
{ id: 3, title: "Front End Devloper" },
];
function JobList() {
return (
<ul>
{posts.map((post) => (
<li key={post.id}>
<Link to={`post/${post.id}`}>{post.title}</Link> {/* Dynamic
Link */}
</li>
))}
</ul> Renders a clickable list of posts.
);
}
Clicking on a post navigates to /job/post/:id.
export default JobList;
Create PostDetails.js (Dynamic Post Page)
import React from "react";
import { useParams } from "react-router-dom";
const posts = [
{ id: 1, title: "Java Devloper", content: "Strong Knowledge of java frameworks" },
{ id: 2, title: "MERN Devloper", content: "Devlope Mobile applications" },
{ id: 3, title: "Front End Devloper", content: "Strong Knowledge of HTML, CSS, Java Script and
react library" },
];
function JobDetails() {
const { id } = useParams(); // Extracts "id" from URL
const post = posts.find((p) => p.id === parseInt(id));
if (!post) {
return <h2> Post Not Found</h2>;
}
return ( Extracts id from the URL using useParams().
<div> Finds the corresponding post and displays its title & content
<h2> {post.title}</h2>
dynamically.
<p>{post.content}</p>
</div> If no post is found, it shows "Post Not Found".
);
}
export default JobDetails;
useParams()
useParams() extracts dynamic parameters from the URL.
🔹 Example:
● If user clicks on "Understanding Components", the URL
becomes /job/post/1.
● useParams() extracts { id: "1" }.
● The component finds the matching post using find().