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 Keys

In React, keys are special attributes used when rendering lists of elements. A key helps React identify which item has been added, removed, or changed between renders.

When we use the map() method to render a list, we should provide a suitable key for each sibling element.

Remember: Keys help React match list items between renders. They should be unique among sibling elements.

2. Why Are Keys Needed?

Suppose a list contains three courses. Later, a new course is added or an existing course is removed. React needs a reliable way to match the items in the updated list with the items from the previous render.

Keys provide that identity and help React determine which list elements need to be updated.

Without a Key

function CourseList() {
    const courses = ["React", "Angular", "ASP.NET Core"];

    return (
        <ul>
            {courses.map((course) => (
                <li>{course}</li>
            ))}
        </ul>
    );
}

This code does not provide a key for each list item. React will show a warning in the development console.

With a Key

function CourseList() {
    const courses = ["React", "Angular", "ASP.NET Core"];

    return (
        <ul>
            {courses.map((course) => (
                <li key={course}>{course}</li>
            ))}
        </ul>
    );
}

In this example, each course name is used as its key. This is suitable because the course names in this array are unique and stable.

3. How Do Keys Work?

The following diagram illustrates how React uses keys to match list items when a list changes.

Previous List ID 1: React ID 2: Angular
↓
Updated List ID 1: React ID 2: Angular ID 3: ASP.NET Core
↓
React Matches Items Uses keys to identify siblings
Important: A key is not a visual part of the rendered list. It is information React uses to identify elements.

4. Using Object IDs as Keys

When an array contains objects, a unique ID property is usually a good choice for the key.

Example

function StudentList() {
    const students = [
        { id: 101, name: "Amit" },
        { id: 102, name: "Priya" },
        { id: 103, name: "Rahul" }
    ];

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

export default StudentList;

Expected Output

  • Amit
  • Priya
  • Rahul

Here, student.id identifies each student, while student.name is displayed on the page.

5. Keys Must Be Unique Among Siblings

Keys should be unique among the elements rendered together in the same list. Duplicate keys can make it difficult for React to match items correctly.

Incorrect Example

const students = [
    { id: 1, name: "Amit" },
    { id: 1, name: "Priya" }
];

{students.map((student) => (
    <li key={student.id}>{student.name}</li>
))}

Both students use the same key, so the keys are not unique among these sibling list items.

Correct Example

const students = [
    { id: 1, name: "Amit" },
    { id: 2, name: "Priya" }
];

{students.map((student) => (
    <li key={student.id}>{student.name}</li>
))}

Each student now has a distinct ID, so React can use the keys to distinguish the list items.

6. Keys Are Not Regular Props

React uses the key internally to identify elements. The key is not passed to the child component as a regular prop. If the component needs the ID, pass it separately.

Example

function Student({ id, name }) {
    return (
        <p>
            {id} - {name}
        </p>
    );
}

function StudentList() {
    const students = [
        { id: 101, name: "Amit" },
        { id: 102, name: "Priya" }
    ];

    return (
        <div>
            {students.map((student) => (
                <Student
                    key={student.id}
                    id={student.id}
                    name={student.name}
                />
            ))}
        </div>
    );
}

Expected Output

101 - Amit

102 - Priya

Note: The key identifies the component in the list. The separate id prop makes the ID available inside Student.

7. Common Mistakes

Mistake 1: Using Duplicate Keys

{students.map((student) => (
    <li key="student">{student.name}</li>
))}

Every item receives the same key. Use a unique identifier for each item instead.

Mistake 2: Using Array Index for a Changing List

{students.map((student, index) => (
    <li key={index}>{student.name}</li>
))}

Index keys can cause incorrect item matching when items are inserted, deleted, or reordered. Prefer stable IDs when the data provides them.

Mistake 3: Expecting key as a Prop

<Student key={student.id} name={student.name} />

The Student component cannot read the key through props.key. Pass a separate prop if the ID is needed inside the component.

8. Best Practices for Keys

  • Use unique, stable IDs from your data whenever possible.
  • Ensure keys are unique among sibling elements.
  • Avoid generating random keys during every render.
  • Avoid array indexes when list items can change order or be inserted or removed.
  • Remember that keys are not passed to components as regular props.

9. Practice Tasks

Complete these tasks to practise using keys in React lists.

Task 1: Create an array of five course objects with unique IDs and display their names using map().
Task 2: Create a list of employee objects containing id and name. Use each employee's ID as the key.
Task 3: Create a product list and explain why product IDs are preferable to array indexes when products can be reordered.
Task 4: Create a child component that displays a student's ID and name. Pass the ID as a regular prop as well as using it for the key.

Summary

Keys are special attributes used when rendering lists in React. They help React identify items between renders when elements are added, removed, or reordered. Keys should be unique among sibling elements and should remain stable between renders. Unique IDs from data are generally a good choice, while array indexes should be avoided for lists that can change. Keys are used internally by React and are not available as regular props inside child components.