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

Optimizing Callbacks with useCallback

In React, functions are commonly passed from parent components to child components as props. Whenever a function component renders again, JavaScript creates new function objects for functions defined inside that component. This can matter when a child component is memoized and compares its props.

React provides the useCallback Hook to cache a function definition between renders. When its dependencies remain unchanged, React can return the same function reference. This can help memoized child components avoid rendering because of a changed callback prop.

Learning objective: Understand useCallback syntax, function references, dependency arrays, stale closures, and how useCallback works with React.memo in practical React applications.

1. What Is useCallback?

useCallback is a React Hook that lets you cache a function definition between renders. React returns the cached function while the dependencies remain unchanged. When a dependency changes, React can return the function created during the new render.

It is especially useful when passing a callback to a memoized child component. Without a stable callback, the child may receive a new function reference on every parent render and render again even though the function performs the same task.

Parent Renders
↓
useCallback Checks Dependencies
↓
Dependencies Unchanged?
↓
Reuse Function Reference
useCallback does not stop a parent from rendering. It preserves a function reference when possible, which can help prevent unnecessary work in memoized child components.

2. Syntax of useCallback

Basic Syntax
import { useCallback } from "react";

const handleClick = useCallback(() => {
    console.log("Button clicked");
}, []);

The syntax contains three important parts:

  • Function: The callback you want to cache.
  • Dependency array: The reactive values used by the callback.
  • Returned function: The function reference you can pass to a child or event handler.

Understanding the Dependency Array

Syntax Meaning
useCallback(() => doSomething(value), [value]) The function reference can be reused while value remains unchanged.
useCallback(() => doSomething(), []) No reactive dependencies are listed. The callback can retain its reference across ordinary re-renders.
useCallback(() => doSomething()) Without a dependency array, the function is not cached across renders.
Include every reactive value used by the callback in the dependency array. Omitting a dependency can make the callback use an outdated value, a problem commonly called a stale closure.

3. Understanding Function References

JavaScript functions are values. Two functions can contain identical code but still be different function objects. This matters because React.memo compares props by reference for function values.

FunctionReferences.jsx
const firstFunction = () => {
    console.log("Hello");
};

const secondFunction = () => {
    console.log("Hello");
};

console.log(firstFunction === secondFunction);

Expected Output

false

Both functions contain the same code, but they are separate function objects and have different references.

Similarly, when a React component creates a callback inside its function body, that callback normally has a new reference after each render. useCallback can preserve the reference when its dependencies have not changed.

4. Example Without useCallback

Consider a parent component with a counter and a memoized child button. The parent creates handleClick on every render. When the counter changes, the new callback reference can cause the memoized child to render again.

Parent.jsx — Without useCallback
import { memo, 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 handleClick = () => {
        console.log("Action performed");
    };

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

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

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

export default Parent;

Expected Behavior

1. Parent renders.

2. ActionButton renders.

3. Clicking Increase Counter updates the parent's state.

4. Parent renders again and creates a new handleClick function.

5. ActionButton receives a new function prop and can render again.

5. Example With useCallback

Now wrap handleClick in useCallback. Since the callback does not depend on changing reactive values, an empty dependency array is suitable for this example.

Parent.jsx — With useCallback
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 handleClick = useCallback(() => {
        console.log("Action performed");
    }, []);

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

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

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

export default Parent;
Counter State Changes
↓
Parent Renders Again
↓
useCallback Reuses handleClick
↓
Same Callback Prop: Child Can Skip Rendering

The counter updates normally. Since handleClick keeps the same reference, ActionButton can skip rendering when its other props remain unchanged.

Clicking Perform Action still calls handleClick and prints "Action performed" in the console.

6. Using useCallback with State

When a callback needs to update state based on its previous value, a functional state update can sometimes avoid including that state variable in the dependency array.

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

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

    const increment = useCallback(() => {
        setCount(previousCount => previousCount + 1);
    }, []);

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

            <button onClick={increment}>
                Increment
            </button>
        </div>
    );
}

export default Counter;

How It Works

  1. The initial count is 0.
  2. The increment callback is created through useCallback.
  3. The user clicks Increment.
  4. The functional updater receives the latest previous count.
  5. React updates the count and renders the component again.
  6. The increment function reference can remain stable.
The functional updater is useful because it receives the latest state value. It avoids relying on a count value captured from an earlier render.

7. Understanding Stale Closures

A closure allows a function to access variables from the scope where it was created. If a callback uses a state value but the dependency array omits that value, the callback may continue using the value captured by an earlier render.

StaleClosure.jsx — Incorrect Example
import { useCallback, useState } from "react";

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

    const showCount = useCallback(() => {
        console.log(count);
    }, []);

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

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

            <button onClick={showCount}>
                Log Count
            </button>
        </div>
    );
}

export default Counter;

In this example, showCount captures the initial count value. Because count is missing from the dependency array, clicking Log Count can continue printing 0 even after the displayed count changes.

Corrected Example

StaleClosure.jsx — Correct Example
const showCount = useCallback(() => {
    console.log(count);
}, [count]);

Now React can return a callback that uses the current count whenever count changes. Always include reactive values used by a callback unless the code is deliberately structured so those values are not needed from the closure.

8. useCallback vs useMemo

useCallback useMemo
Caches a function definition. Caches a calculation result.
Useful for stable callback props. Useful for expensive calculations.
useCallback(fn, [deps]) useMemo(() => calculate(), [deps])
Often useful with React.memo. Often useful for derived values such as filtered lists.

9. When Should You Use useCallback?

  • When passing callbacks to memoized child components.
  • When a callback is a dependency of another Hook.
  • When a stable function reference avoids measurable unnecessary work.
  • When a callback can be reused while its dependencies remain unchanged.

10. When Should You Avoid useCallback?

  • When the function is simple and no optimization benefit is expected.
  • When the child is not memoized and a stable reference does not help.
  • When adding useCallback makes the code harder to understand without measurable benefit.
  • When dependencies change on every render, preventing useful reuse.
useCallback does not make the function body execute faster when the function is called. It caches the function reference. Use it for a specific optimization need, not automatically for every event handler.

11. Common Mistakes

  1. Forgetting reactive dependencies.
  2. Using an empty dependency array when the callback reads changing state or props.
  3. Expecting useCallback to prevent the parent from rendering.
  4. Using useCallback without a reason to preserve the function reference.
  5. Assuming a cached function reference makes the function execution itself faster.
  6. Expecting React.memo to help when other props still change.

12. Practice Tasks

Task 1: Stable Callback

Create a Parent component with a counter and a memoized child button. Observe the child's render behavior before and after using useCallback.

Task 2: Counter with Functional Update

Create an increment function using useCallback and a functional state updater. Check whether the callback can use an empty dependency array.

Task 3: Stale Closure

Create a callback that reads count. First omit count from the dependencies, observe the result, and then correct the dependency array.

Task 4: Parent and Child

Pass a callback to a memoized StudentCard component. Change an unrelated parent state and explain why a stable callback can allow the child to skip rendering.

Task 5: Explain the Difference

Explain useCallback, useMemo, and React.memo with one practical example for each.

Summary

The useCallback Hook caches a function reference between renders while its dependencies remain unchanged. It is useful when stable callbacks help memoized child components avoid unnecessary rendering or when a function is used as a Hook dependency. Correct dependency arrays prevent stale closures, and functional state updates can simplify callbacks that depend on previous state. Unlike useMemo, which caches a calculation result, useCallback caches a function definition. At CIIT Training Institute, practice callback memoization with parent-child components and use it when a measurable performance benefit justifies the added complexity.