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

1. Introduction to Sorting Lists

Sorting means arranging items in a particular order, such as alphabetical order or numerical order. In React, we can use JavaScript array methods to sort data before displaying it.

The sort() method sorts the elements of an array. When working with React state or props, avoid modifying the original array directly. Create a copy before sorting.

Remember: Use [...array].sort() to sort a copy of an array without changing the original array.

2. Sorting Strings Alphabetically

The sort() method can arrange strings in alphabetical order using JavaScript's default string sorting behavior.

Example

const courses = [
    "React",
    "Angular",
    "JavaScript",
    "ASP.NET Core"
];

const sortedCourses = [...courses].sort();

console.log(sortedCourses);

Expected Output

["ASP.NET Core", "Angular", "JavaScript", "React"]

The spread operator creates a copy of the courses array. The sort() method then sorts the copied array.

3. Sorting Numbers

By default, sort() compares array elements as strings. For numerical sorting, provide a comparison function.

Ascending Order

const numbers = [40, 5, 100, 25, 10];

const ascendingNumbers = [...numbers].sort(
    (a, b) => a - b
);

console.log(ascendingNumbers);

Expected Output

[5, 10, 25, 40, 100]

Descending Order

const descendingNumbers = [...numbers].sort(
    (a, b) => b - a
);

console.log(descendingNumbers);

Expected Output

[100, 40, 25, 10, 5]
Explanation: Use a - b for ascending numerical order and b - a for descending numerical order.

4. How Sorting Works

The following diagram shows how an unsorted array is copied, sorted, and prepared for rendering.

Original Array 40, 5, 100, 25
↓
Copy the Array [...numbers]
↓
sort((a, b) => a - b) Arrange in ascending order
↓
Sorted Array 5, 25, 40, 100
Important: sort() modifies the array on which it is called. Copying the array first prevents unintended changes to the original data.

5. Sorting a List of Objects

When an array contains objects, we can sort the objects using one of their properties, such as name or price.

Example: Sorting Students by Name

function StudentList() {
    const students = [
        { id: 1, name: "Rahul" },
        { id: 2, name: "Amit" },
        { id: 3, name: "Priya" }
    ];

    const sortedStudents = [...students].sort(
        (a, b) => a.name.localeCompare(b.name)
    );

    return (
        <div>
            <h2>Students in Alphabetical Order</h2>

            <ul>
                {sortedStudents.map((student) => (
                    <li key={student.id}>
                        {student.name}
                    </li>
                ))}
            </ul>
        </div>
    );
}

export default StudentList;

Expected Output

Students in Alphabetical Order

  • Amit
  • Priya
  • Rahul

6. Sorting Products by Price

We can sort products by their numerical price property to display the lowest-priced products first.

Example

function ProductList() {
    const products = [
        { id: 1, name: "Monitor", price: 7000 },
        { id: 2, name: "Mouse", price: 500 },
        { id: 3, name: "Keyboard", price: 800 }
    ];

    const sortedProducts = [...products].sort(
        (a, b) => a.price - b.price
    );

    return (
        <div>
            <h2>Products by Price

Expected Output

Products by Price

  • Mouse - ₹500
  • Keyboard - ₹800
  • Monitor - ₹7000

The comparison function sorts products from the lowest price to the highest price. Each product retains its original ID for use as a React key.

7. Sorting in Descending Order

To display the highest-priced product first, reverse the comparison function.

const sortedProducts = [...products].sort(
    (a, b) => b.price - a.price
);

Expected Order

  • Monitor - ₹7000
  • Keyboard - ₹800
  • Mouse - ₹500
Remember: The comparison function determines the order in which elements appear in the sorted array.

8. Common Mistakes

Mistake 1: Sorting Numbers Without a Comparator

const numbers = [5, 100, 25, 10];

const result = [...numbers].sort();

Default sorting compares values as strings, so it does not guarantee the expected numerical order.

Correct Code

const result = [...numbers].sort(
    (a, b) => a - b
);

// Result: [5, 10, 25, 100]

Mistake 2: Modifying the Original Array

products.sort(
    (a, b) => a.price - b.price
);

sort() changes the array on which it is called. Avoid directly sorting arrays received through props or held in React state.

Correct Code

const sortedProducts = [...products].sort(
    (a, b) => a.price - b.price
);

9. Practice Tasks

Complete these tasks to practise sorting lists in React.

Task 1: Sort an array of five numbers in ascending order.
Task 2: Sort the same numbers in descending order.
Task 3: Create an array of student objects and display their names in alphabetical order.
Task 4: Create product objects with IDs, names, and prices. Display them from highest price to lowest price.
Task 5: Sort a copied array and verify that the original array remains unchanged.

Summary

Sorting lists in React can be performed using JavaScript's sort() method before rendering the data. A comparison function such as a - b sorts numbers in ascending order, while b - a sorts them in descending order. Object arrays can be sorted by properties such as name or price. Because sort() modifies the array on which it is called, creating a copy before sorting helps avoid unintended mutations of React state or props.