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

Avoiding Unnecessary Re-Renders in React

In React, components render again when React needs to calculate an updated user interface. This behavior is necessary for displaying new state and props. However, some components may perform additional rendering work even when their displayed information has not changed.

Avoiding unnecessary re-renders means reducing work that does not contribute to a meaningful UI update. It is especially useful in applications containing large component trees, complex calculations, long lists, or expensive UI components.

Learning objective: By the end of this lesson, you will understand how component structure, state placement, React.memo, stable props, and performance profiling can help reduce unnecessary rendering work.

1. What Is an Unnecessary Re-Render?

An unnecessary re-render is a render that performs avoidable work without providing a useful change to the user interface. For example, a parent component may update a counter while a separate child component displays fixed information.

If that child is expensive to render and does not need new information, rendering it again may waste resources. In a small application, the cost may be negligible. In a larger application, repeated work can affect responsiveness.

Parent State Changes
↓
Parent Renders Again
↓
Unchanged Child Also Renders
↓
Extra Rendering Work
A child rendering again is not automatically a problem. Optimization is useful when measurements show that the extra rendering work meaningfully affects performance.

2. Example Without Optimization

Consider a parent component with a counter and a child component displaying a student's name. Clicking the counter button updates the parent's state. The child can also render again, even though its name has not changed.

Parent.jsx — Before Optimization
import { useState } from "react";

function StudentInfo({ name }) {
    console.log("StudentInfo rendered");

    return (
        <div>
            <h3>Student Name: {name}</h3>
            <p>Welcome to CIIT Training Institute.</p>
        </div>
    );
}

function Parent() {
    const [count, setCount] = useState(0);

    console.log("Parent rendered");

    return (
        <div>
            <h2>Counter: {count}</h2>

            <button onClick={() => setCount(c => c + 1)}>
                Increase Counter
            </button>

            <StudentInfo name="Samiksha" />
        </div>
    );
}

export default Parent;

How This Example Works

  1. React renders the Parent component for the initial display.
  2. Parent displays the counter and renders StudentInfo.
  3. StudentInfo displays the name Samiksha.
  4. The user clicks Increase Counter.
  5. The counter state changes, causing Parent to render again.
  6. StudentInfo may also render again, although its name remains the same.

Expected Console Behavior

Initial render:

Parent rendered

StudentInfo rendered

After clicking the counter button:

Parent rendered

StudentInfo rendered

The exact number of console messages can differ in development when React Strict Mode is enabled. The important concept is that a normal parent update can also cause its child to render again.

3. Solution One: Use React.memo

React.memo is a higher-order component that can skip rendering a function component when its props are unchanged according to React's default shallow comparison. It is useful when a component receives the same props repeatedly and its rendering work is worth avoiding.

Parent.jsx — Using React.memo
import { memo, useState } from "react";

const StudentInfo = memo(function StudentInfo({ name }) {
    console.log("StudentInfo rendered");

    return (
        <div>
            <h3>Student Name: {name}</h3>
            <p>Welcome to CIIT Training Institute.</p>
        </div>
    );
});

function Parent() {
    const [count, setCount] = useState(0);

    console.log("Parent rendered");

    return (
        <div>
            <h2>Counter: {count}</h2>

            <button onClick={() => setCount(c => c + 1)}>
                Increase Counter
            </button>

            <StudentInfo name="Samiksha" />
        </div>
    );
}

export default Parent;

Expected Behavior After Optimization

Counter State Changes
↓
Parent Renders Again
↓
StudentInfo Props Compared
↓
Same Props: Child Render Can Be Skipped

Initial render: Parent and StudentInfo render.

After counter click: Parent renders again.

Because the name prop remains the same, React.memo can skip the StudentInfo render.

React.memo is an optimization, not a guarantee that a component will never render again. A component can still render when its own state or a context value it consumes changes.

4. Solution Two: Keep State Close to Where It Is Used

State placement is one of the simplest ways to reduce unnecessary rendering. If a piece of state is required by only one small component, it usually does not need to live in a high-level parent.

When state is stored in a large parent, every update to that state causes the parent to render again. Its descendant components may also render. Moving the state into the component that needs it can reduce the number of components affected by that update.

Before: State in a Large Parent

Before.jsx
import { useState } from "react";

function SearchBox({ query, setQuery }) {
    return (
        <input
            value={query}
            onChange={e => setQuery(e.target.value)}
            placeholder="Search students"
        />
    );
}

function StudentList() {
    console.log("StudentList rendered");

    return <p>Student list content</p>;
}

function Dashboard() {
    const [query, setQuery] = useState("");

    return (
        <div>
            <SearchBox query={query} setQuery={setQuery} />
            <StudentList />
        </div>
    );
}

export default Dashboard;

Here, typing in the search field updates the query state in Dashboard. Dashboard renders again, and StudentList may render again even though it does not use the query.

After: Move the State into SearchBox

After.jsx
import { useState } from "react";

function SearchBox() {
    const [query, setQuery] = useState("");

    return (
        <input
            value={query}
            onChange={e => setQuery(e.target.value)}
            placeholder="Search students"
        />
    );
}

function StudentList() {
    console.log("StudentList rendered");

    return <p>Student list content</p>;
}

function Dashboard() {
    return (
        <div>
            <SearchBox />
            <StudentList />
        </div>
    );
}

export default Dashboard;
In this version, typing updates SearchBox's local state. Dashboard does not need to render again for every keystroke, so StudentList is not affected by those search-field updates.

This approach works when the query is needed only inside SearchBox. If another component needs the query, keep the state at the nearest common parent that needs to share it.

5. Solution Three: Avoid Unnecessary Object and Function Props

React.memo compares props shallowly. If a parent creates a new object or function during every render, the reference may be different even when the content looks the same.

Example: A New Object on Every Render

UnstableProps.jsx
import { memo, useState } from "react";

const StudentCard = memo(function StudentCard({ student }) {
    console.log("StudentCard rendered");

    return <p>Student: {student.name}</p>;
});

function Parent() {
    const [count, setCount] = useState(0);

    const student = { name: "Samadhan" };

    return (
        <div>
            <button onClick={() => setCount(c => c + 1)}>
                Count: {count}
            </button>

            <StudentCard student={student} />
        </div>
    );
}

export default Parent;

Every time Parent renders, it creates a new student object. Although the name remains Samadhan, the object reference changes. Therefore, React.memo sees a changed prop and cannot skip StudentCard based on its default comparison.

Improved Version: Pass a Stable Primitive Prop

StableProps.jsx
import { memo, useState } from "react";

const StudentCard = memo(function StudentCard({ name }) {
    console.log("StudentCard rendered");

    return <p>Student: {name}</p>;
});

function Parent() {
    const [count, setCount] = useState(0);

    return (
        <div>
            <button onClick={() => setCount(c => c + 1)}>
                Count: {count}
            </button>

            <StudentCard name="Samadhan" />
        </div>
    );
}

export default Parent;
The name prop is a string with the same value on each render. With React.memo, StudentCard can skip rendering when only the counter changes.

Sometimes objects or functions must be passed as props. In those cases, use tools such as useMemo or useCallback only when stable references are useful and the optimization is justified.

6. Solution Four: Use useMemo and useCallback When Appropriate

useMemo caches a calculation result between renders when its dependencies have not changed. useCallback caches a function definition between renders under the same dependency condition. They can be useful when expensive calculations or memoized child components would otherwise receive changing references.

MemoizedChild.jsx
import { memo, useCallback, useState } from "react";

const ActionButton = memo(function ActionButton({ onAction }) {
    console.log("ActionButton rendered");

    return (
        <button onClick={onAction}>
            Perform Action
        </button>
    );
});

function Parent() {
    const [count, setCount] = useState(0);
    const [message, setMessage] = useState("Ready");

    const handleAction = useCallback(() => {
        setMessage("Action completed");
    }, []);

    return (
        <div>
            <h2>Count: {count}</h2>
            <p>Status: {message}</p>

            <button onClick={() => setCount(c => c + 1)}>
                Increase Counter
            </button>

            <ActionButton onAction={handleAction} />
        </div>
    );
}

export default Parent;

The handleAction function retains its reference between renders because it has no changing dependencies. As a result, ActionButton can skip rendering when the counter changes, provided its other props remain unchanged.

Do not add useMemo or useCallback to every value automatically. They add complexity and have their own costs. First determine whether a changing reference is actually causing avoidable work.

7. Use React Developer Tools Profiler

React Developer Tools includes a Profiler that helps you record rendering activity. It can help identify which components rendered, how much time rendering took, and whether an optimization made a measurable difference.

  1. Install or open React Developer Tools in your browser.
  2. Open the React DevTools Profiler tab.
  3. Start recording a user interaction.
  4. Perform the action that seems slow.
  5. Stop recording and inspect the component render information.
  6. Apply a targeted optimization and record again.
Profiling is more reliable than assuming that a component is slow just because it renders again. Compare behavior before and after your changes.

8. Comparison of Optimization Techniques

Technique Purpose When It Helps
React.memo Can skip rendering a component when props are unchanged. Expensive child components receiving stable props.
Local State Limits updates to the component that owns the state. State is used by only one small part of the UI.
useMemo Caches a calculation result. Expensive calculations with unchanged dependencies.
useCallback Caches a function definition. Stable callback references are useful to memoized children.
Profiler Measures rendering behavior. Finding and verifying actual performance bottlenecks.

9. Common Mistakes to Avoid

  • Trying to prevent every re-render, including necessary updates.
  • Using React.memo without considering the cost of rendering.
  • Creating new object and function props for memoized children unnecessarily.
  • Moving shared state too low when multiple components need it.
  • Adding useMemo and useCallback everywhere without measuring.
  • Assuming every re-render causes a DOM update.
  • Ignoring React DevTools and optimizing based only on guesses.

10. Practice Tasks

Task 1: Identify Re-Renders

Create a Parent component with a counter and a StudentInfo child. Add console messages to both components and observe what happens when the counter changes.

Task 2: Apply React.memo

Wrap StudentInfo with React.memo. Click the counter button and compare the console output before and after the change.

Task 3: Move State

Create a dashboard with a search input and a student list. Move search state into the search component and observe whether the dashboard and list still render on every keystroke.

Task 4: Test Stable Props

Pass an object prop to a memoized component. Then replace it with a primitive prop and compare the rendering behavior.

Task 5: Profile an Application

Record a few interactions with React Developer Tools Profiler. Identify one component that performs avoidable work and explain how you would test a possible optimization.

Summary

Avoiding unnecessary re-renders helps React applications reduce avoidable work while preserving correct UI behavior. React.memo can skip rendering when props remain unchanged, and placing state close to the components that use it can prevent unrelated parts of the application from being affected by local updates. Stable object and function references may also help memoized components, while useMemo and useCallback are useful for specific, measured cases. React Developer Tools Profiler helps identify bottlenecks and verify improvements. At CIIT Training Institute, practice these techniques with real components and optimize only when there is a clear performance benefit.