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

useCallback Hook

Learn how to use the useCallback Hook to cache function definitions between renders and optimize components when stable function references are useful.

1. What Is the useCallback Hook?

The useCallback Hook is a built-in React Hook that caches a function definition between renders. React can reuse the cached function while its dependencies remain unchanged.

It is useful when passing callbacks to memoized child components or when a function is used as a dependency of another Hook.

Remember: useCallback is a performance optimization. It does not automatically make every function or component faster.

2. Syntax of useCallback

The basic syntax is:

const cachedFunction = useCallback(() => {
    // Function logic
}, [dependencies]);
  • Function: The function definition that React can cache.
  • Dependencies: Reactive values used inside the function.
  • cachedFunction: The function returned by useCallback.
Important: React returns the cached function when its dependencies have not changed. When a dependency changes, React can return a new function definition.

3. How useCallback Works

React compares the dependencies between renders. If the dependencies remain unchanged, the cached function can be reused. Otherwise, React uses the new function definition.

Component Renders
→
Check Dependencies
→
Reuse or Update Function
→
Use Callback
Remember: useCallback caches a function definition, whereas useMemo caches the result of a calculation.

4. Example: Using useCallback

In this example, useCallback creates a function that displays a message when a button is clicked.

Example Code

import { useCallback, useState } from "react";

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

    const showMessage = useCallback(() => {
        console.log("Hello from React!");
    }, []);

    return (
        <div>
            <h2>useCallback Example</h2>

            <p>Count: {count}</p>

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

            <button onClick={showMessage}>
                Show Message
            </button>
        </div>
    );
}

export default App;

Expected Output

useCallback Example

Count: 0

After clicking Increase Count: Count: 1

After clicking Show Message, the console displays:

Hello from React!
Explanation: The showMessage function is wrapped in useCallback with an empty dependency array because it does not use any reactive values from the component. The function can be reused across renders.

5. useCallback with React.memo

A new function is normally created when a component renders. When a function is passed as a prop to a memoized child component, a different function reference can cause the child to render again. useCallback can help keep that reference stable when its dependencies do not change.

Example Code

import {
    memo,
    useCallback,
    useState
} from "react";

const Child = memo(function Child({ onClick }) {
    console.log("Child rendered");

    return (
        <button onClick={onClick}>
            Click Child
        </button>
    );
});

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

    const handleChildClick = useCallback(() => {
        console.log("Child button clicked");
    }, []);

    return (
        <div>
            <h2>Memoized Child Example</h2>

            <p>Count: {count}</p>

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

            <Child onClick={handleChildClick} />
        </div>
    );
}

export default App;

Expected Output

Memoized Child Example

Count: 0

[ Increase Count ]

[ Click Child ]

Clicking Increase Count updates the parent count. The memoized child can skip rendering because its callback prop remains the same.

Clicking Click Child displays a message in the console.

Explanation: React.memo can skip a child render when its props have not changed. useCallback helps keep the callback prop stable while its dependencies remain unchanged. Other changes, such as context updates, can still cause a render.

6. Understanding Dependencies

If a callback uses state or props, include those reactive values in the dependency array so that the function uses the latest values.

Example Code

import { useCallback, useState } from "react";

function App() {
    const [name, setName] = useState("Samadhan");

    const showName = useCallback(() => {
        console.log(name);
    }, [name]);

    return (
        <div>
            <h2>Callback Dependencies</h2>

            <p>Name: {name}</p>

            <button onClick={() =>
                setName("Samiksha")
            }>
                Change Name
            </button>

            <button onClick={showName}>
                Show Name
            </button>
        </div>
    );
}

export default App;

Expected Output

Initially: Name: Samadhan

After clicking Change Name: Name: Samiksha

Click Show Name.

Console output: Samiksha
Explanation: The name variable is included in the dependency array. When name changes, React provides a callback that uses the updated name value.

7. Difference Between useMemo and useCallback

  • useMemo: Caches the result of a calculation.
  • useCallback: Caches a function definition.
  • useMemo example: Calculating a total price from quantity and price.
  • useCallback example: Keeping a callback reference stable when passing it to a memoized child component.
const total = useMemo(() => {
    return price * quantity;
}, [price, quantity]);

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

8. Important Points About useCallback

  • Import useCallback from React.
  • Call Hooks at the top level of a component or custom Hook.
  • Include all reactive values used by the callback in its dependency array.
  • useCallback returns a function; it does not execute that function automatically.
  • It is most useful when stable function identity provides a real performance benefit.
  • Avoid using useCallback unnecessarily for every function in a component.

9. Practice Tasks

Complete the following exercises:

  1. Create a function using useCallback that logs a message.
  2. Create a counter and a callback that displays its value.
  3. Pass a callback to a child component wrapped in React.memo.
  4. Create a callback that displays a student's name and update it when the name changes.
  5. Explain the difference between useMemo and useCallback.

Summary

The useCallback Hook caches a function definition between renders while its dependencies remain unchanged. It is particularly useful when passing callbacks to memoized child components or when a function is used as a dependency of another Hook. All reactive values used by the callback should be included in its dependency array. Unlike useMemo, which caches a calculated value, useCallback caches a function definition. Understanding when to use callback memoization helps developers optimize React applications at CIIT Training Institute.