Master React From Scratch

Clear, practical, and structured React lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to React
Introduction to React What Is React? Features of React Advantages of React Limitations of React Uses of React React vs JavaScript React Architecture
2. React Getting Started
Getting Started Introduction Prerequisites Installing Node.js and npm Creating a React Project with Vite React Project Structure Running React Application Your First React Application
3. JSX
JSX Introduction What Is JSX? JavaScript Expressions JSX Attributes Rendering JSX Elements JSX Children React Fragments JSX Rules and Best Practices JSX vs HTML
4. React Components
Components Introduction Functional Components Class Components Component Composition Reusable Components Component Tree Component Lifecycle Import and Export Components
5. React Props
Props Introduction What Are Props? Passing Props to Components Props Destructuring Default Props Values Children Props Typing Props with TypeScript Props vs State
6. React State
State Introduction What Is State? useState Hook Updating State Functional State Updates State with Objects State with Arrays State Immutability Lifting State Up
7. React Events
Events Introduction Handling Events Passing Arguments to Event Handlers Synthetic Events Form Events Keyboard and Mouse Events Event Propagation
8. Conditional Rendering
Conditional Rendering Introduction If-Else Rendering Ternary Operator Logical AND Operator Element Variables Preventing Rendering Multiple Conditions Conditional CSS Classes
9. Lists and Keys
Lists and Keys Introduction Rendering Lists with map() Understanding Keys Choosing Unique Keys Lists of Objects Filtering Lists Sorting Lists Empty Lists and Conditional Rendering
10. React Forms
Forms Introduction Handling Forms Controlled Components Uncontrolled Components Handling Input Fields Checkboxes and Radio Buttons Select and Textarea Form Validation Form Submission
11. React Hooks
Hooks Introduction useState Hook useEffect Hook Effect Dependencies and Cleanup useRef Hook useReducer Hook useMemo Hook useCallback Hook Custom Hooks Rules of Hooks
12. React Context API
Context API Introduction createContext useContext Context Provider Reading Context Updating Context Using Multiple Contexts Context API vs Props Context API Best Practices
13. React Routing
Routing Introduction Introduction to React Router Installing React Router BrowserRouter Setup Routes and Route Components Link and NavLink Programmatic Navigation URL Parameters and useParams Nested Routes Not Found Routes Protected Routes
14. API Integration
API Integration Introduction Fetch API Async/Await with API Calls Displaying API Data Loading and Error States Sending POST Requests API Error Handling Using Axios Custom Fetch Hook API Environment Variables
15. State Management
State Management Introduction Global State Prop Drilling Introduction to Redux Redux Core Concepts Redux Toolkit Store and Slices useSelector and useDispatch Async Operations with Redux Toolkit State Management Best Practices
16. React Performance
Performance Introduction Understanding Re-Renders Avoiding Unnecessary Re-Renders React.memo useMemo Optimization useCallback Optimization React Developer Tools and Profiler Lazy Loading Components Code Splitting Optimizing Large Lists Performance Best Practices

URL Parameters and useParams

In this lesson, we will learn how to create dynamic routes, pass identifiers through URLs, and read those values using the useParams hook.

1. What Are URL Parameters?

URL parameters are values included in a URL to identify a particular resource. They are useful when many records share the same page structure but each record has different information.

For example, a training institute may have many students. Instead of creating a separate component for every student, we can create one StudentDetails component and pass a different student ID through the URL.

/students/101
↓
StudentDetails Component
↓
Displays Student ID: 101

Remember: A URL parameter lets a route receive a changing value without creating a separate route definition for every possible value.

2. What Is a Dynamic Route?

A dynamic route contains a parameter whose value can change. In React Router, a parameter is declared by placing a colon before its name in the route path.

Route Definition

<Route
    path="/students/:studentId"
    element={<StudentDetails />}
/>

Here, :studentId is a dynamic parameter. React Router can match URLs such as:

  • /students/101
  • /students/102
  • /students/205

All these URLs can render the same StudentDetails component. The value of studentId changes according to the URL.

3. What Is the useParams Hook?

useParams is a React Router hook that returns an object containing the dynamic parameters from the currently matched route.

Import useParams

import { useParams } from 'react-router-dom';

Basic Syntax

const params = useParams();

If the current URL is /students/101 and the route path is /students/:studentId, useParams returns an object similar to:

{
    studentId: "101"
}

Important: URL parameters are strings. If you need a number for calculations or numeric comparisons, convert and validate the value explicitly.

4. Read a Student ID Using useParams

Let's create a StudentDetails component that reads the student ID from the current URL and displays it on the page.

import { useParams } from 'react-router-dom';

function StudentDetails() {
    const { studentId } = useParams();

    return (
        <div>
            <h2>Student Details</h2>
            <p>Student ID: {studentId}</p>
        </div>
    );
}

export default StudentDetails;

Explanation

  1. Import useParams from React Router.
  2. Call useParams inside StudentDetails.
  3. Extract the studentId parameter from the returned object.
  4. Display studentId using JSX.

Expected Output

When the URL is /students/101:

Student Details
Student ID: 101

When the URL is /students/205:

Student Details
Student ID: 205

5. Configure a Dynamic Route

The route parameter must be defined in the Route path before the component can read it using useParams.

import {
    BrowserRouter,
    Routes,
    Route
} from 'react-router-dom';

import StudentDetails from './StudentDetails';

function App() {
    return (
        <BrowserRouter>
            <Routes>
                <Route
                    path="/students/:studentId"
                    element={<StudentDetails />}
                />
            </Routes>
        </BrowserRouter>
    );
}

export default App;

If BrowserRouter is already configured in main.jsx, do not add another BrowserRouter in App.jsx. Place Routes directly inside the existing router instead.

6. Use Multiple URL Parameters

A route can contain more than one dynamic parameter. For example, a course may belong to a particular student.

Route Definition

<Route
    path="/students/:studentId/courses/:courseId"
    element={<StudentCourseDetails />}
/>

Read Both Parameters

import { useParams } from 'react-router-dom';

function StudentCourseDetails() {
    const { studentId, courseId } = useParams();

    return (
        <div>
            <h2>Student Course Details</h2>
            <p>Student ID: {studentId}</p>
            <p>Course ID: {courseId}</p>
        </div>
    );
}

export default StudentCourseDetails;

Example URL

/students/101/courses/25

Expected Output

Student Course Details
Student ID: 101
Course ID: 25

7. Dynamic Course Details Page

A common real-world example is displaying different course details using a course ID in the URL.

import { useParams } from 'react-router-dom';

const courses = {
    "101": "React Development",
    "102": "Dot Net Development",
    "103": "Data Analytics"
};

function CourseDetails() {
    const { courseId } = useParams();

    const courseName = courses[courseId];

    if (!courseName) {
        return <h2>Course Not Found</h2>;
    }

    return (
        <div>
            <h2>Course Details</h2>
            <p>Course ID: {courseId}</p>
            <p>Course Name: {courseName}</p>
        </div>
    );
}

export default CourseDetails;

In this example, the course information is stored in a JavaScript object for demonstration. A real application can fetch course details from an API using the course ID.

Expected Output for /courses/101

Course Details
Course ID: 101
Course Name: React Development

Expected Output for /courses/999

Course Not Found

8. URL Parameters vs Query Parameters

URL parameters and query parameters both carry information in a URL, but they use different formats and are accessed differently.

Feature URL Parameter Query Parameter
Example URL /courses/101 /courses?category=react
Location Part of the route path After the question mark (?)
Common use Identifying a particular resource Filtering, sorting, and search options
Typical access useParams() useLocation() with URLSearchParams

Remember: useParams reads parameters declared in the route path. Query parameters such as category=react are usually read from the URL search string.

9. Common Mistakes

Mistake 1: Forgetting the colon

// Dynamic parameter
<Route path="/students/:studentId" element={<StudentDetails />} />

The colon identifies studentId as a dynamic route parameter.

Mistake 2: Using a different parameter name

If the route uses :studentId, read studentId from useParams. The property name must match the name defined in the route.

Mistake 3: Treating a URL parameter as a number

Parameters are strings. Convert and validate them before performing numeric operations.

const { studentId } = useParams();
const id = Number(studentId);

if (!Number.isInteger(id) || id <= 0) {
    return <h2>Invalid Student ID</h2>;
}

Mistake 4: Expecting a missing record to be handled automatically

useParams reads the parameter value; it does not check whether a corresponding student or course exists. Your application must handle missing records separately.

Practice Tasks

  1. Create a dynamic route for /students/:studentId.
  2. Display the student ID using useParams.
  3. Create a route for /courses/:courseId.
  4. Display a course name based on the course ID.
  5. Create a route with studentId and courseId parameters.
  6. Display both values using useParams.
  7. Handle an invalid course ID with a Course Not Found message.
  8. Explain the difference between URL parameters and query parameters.
  9. Validate a numeric ID before using it in a calculation.

Summary

Dynamic routes allow a single React component to display different information based on URL values. Parameters are defined with a colon in the route path, such as /students/:studentId, and the useParams hook reads those values from the matched route. You can use one or multiple parameters for student details, course details, and other dynamic pages. Remember that URL parameters are strings and that your application must handle invalid values or missing records. In the next lesson, we will learn nested routes.