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

Programmatic Navigation with useNavigate

In this lesson, we will learn how to navigate between routes using JavaScript logic, button clicks, form submissions, and other application events with the useNavigate hook.

1. What Is Programmatic Navigation?

Programmatic navigation means changing the current route through application logic instead of asking the user to click a normal navigation link.

For example, after a user submits a form successfully, the application can automatically navigate to a dashboard. Similarly, after adding a course to a shopping cart, the application may navigate to the cart page.

User Performs an Action
↓
React Executes Event Handler
↓
useNavigate Changes the Route
↓
Destination Page Is Displayed

Remember: Use programmatic navigation when navigation should happen because of an event or application condition.

2. What Is the useNavigate Hook?

useNavigate is a React Router hook that returns a function for navigating to another route. You can call this function inside an event handler or another suitable part of your component logic.

Import useNavigate

import { useNavigate } from 'react-router-dom';

Basic Syntax

const navigate = useNavigate();

navigate('/courses');

Here, useNavigate returns the navigate function. Calling navigate with /courses changes the current route to that destination.

Important: Call useNavigate at the top level of a React component or custom hook, not inside an event handler, loop, or conditional statement. Call the returned navigate function inside the event handler.

3. Navigate When a Button Is Clicked

One common use of useNavigate is to navigate to another page when the user clicks a button.

Example

import { useNavigate } from 'react-router-dom';

function Home() {
    const navigate = useNavigate();

    function openCourses() {
        navigate('/courses');
    }

    return (
        <div>
            <h2>Home Page</h2>

            <button onClick={openCourses}>
                View Courses
            </button>
        </div>
    );
}

export default Home;

Explanation

  1. Import useNavigate from React Router.
  2. Call useNavigate inside the Home component.
  3. Store the returned function in navigate.
  4. Define the openCourses event handler.
  5. Call navigate('/courses') when the button is clicked.

Expected Behavior

Home Page

[ View Courses ]

Clicking View Courses navigates to /courses, where the matching Courses route should render.

4. Navigate After Form Submission

Suppose a student enters their name into a registration form. After the form is submitted successfully, we can navigate to a confirmation page.

import { useState } from 'react';
import { useNavigate } from 'react-router-dom';

function Registration() {
    const [studentName, setStudentName] = useState('');
    const navigate = useNavigate();

    function handleSubmit(event) {
        event.preventDefault();

        if (studentName.trim() !== '') {
            navigate('/confirmation');
        }
    }

    return (
        <form onSubmit={handleSubmit}>
            <h2>Student Registration</h2>

            <input
                type="text"
                value={studentName}
                onChange={(event) =>
                    setStudentName(event.target.value)
                }
                placeholder="Enter student name"
            />

            <button type="submit">
                Register
            </button>
        </form>
    );
}

export default Registration;

Explanation

  • useState stores the value entered by the student.
  • onChange updates studentName as the user types.
  • onSubmit calls handleSubmit when the form is submitted.
  • event.preventDefault() prevents the browser's default form submission.
  • If the name is not empty, navigate moves to /confirmation.

Note: This is a basic client-side example. A real registration form should validate and save the information through the appropriate backend before navigating to the confirmation page.

5. Navigate After a Successful Login

In an application, a successful login may redirect the user to a dashboard. Navigation should happen only after the application has confirmed that authentication succeeded.

import { useNavigate } from 'react-router-dom';

function Login() {
    const navigate = useNavigate();

    async function handleLogin() {
        // Replace this with real authentication.
        const loginSuccessful = true;

        if (loginSuccessful) {
            navigate('/dashboard', { replace: true });
        }
    }

    return (
        <div>
            <h2>Login Page</h2>

            <button onClick={handleLogin}>
                Login
            </button>
        </div>
    );
}

export default Login;

Explanation

In this simplified example, loginSuccessful represents the result of an authentication process. In a real application, replace it with the actual result returned by your login service or API.

The option replace: true replaces the current history entry instead of adding another entry. This can prevent the Login page from remaining as the immediately previous history entry.

Never treat a hardcoded success value as real authentication. Protect sensitive routes with proper authentication and authorization checks.

6. Navigate Backward and Forward

The navigate function can also move through browser history using a numeric argument.

Go Back

navigate(-1);

This navigates to the previous history entry when one exists.

Go Forward

navigate(1);

This navigates to the next history entry when one exists.

Complete Example

import { useNavigate } from 'react-router-dom';

function CourseDetails() {
    const navigate = useNavigate();

    return (
        <div>
            <h2>Course Details</h2>

            <button onClick={() => navigate(-1)}>
                Go Back
            </button>

            <button onClick={() => navigate(1)}>
                Go Forward
            </button>
        </div>
    );
}

export default CourseDetails;

The previous or next history entry may not exist. For example, navigate(-1) may leave the application if the user arrived from another website.

7. Passing State During Navigation

Sometimes a component needs to pass temporary information to the destination route. The navigate function supports a state option for this purpose.

Send Data from One Component

import { useNavigate } from 'react-router-dom';

function Courses() {
    const navigate = useNavigate();

    function openDetails() {
        navigate('/course-details', {
            state: {
                courseName: 'React Development'
            }
        });
    }

    return (
        <button onClick={openDetails}>
            View Course Details
        </button>
    );
}

export default Courses;

Read State in the Destination Component

import { useLocation } from 'react-router-dom';

function CourseDetails() {
    const location = useLocation();

    const courseName =
        location.state?.courseName ?? 'Course Details';

    return (
        <h2>{courseName}</h2>
    );
}

export default CourseDetails;

The destination component reads the navigation state through useLocation. Optional chaining and the fallback value prevent an error if the state is missing.

Navigation state is useful for temporary UI information. Do not rely on it as the only source for essential data; users may open a URL directly or refresh the page.

8. Difference Between Link and useNavigate

Feature Link useNavigate
Purpose Provides a navigation link for the user. Changes routes through application logic.
Typical use Navigation menus and page links. Form submission, event handlers, and redirects.
How it is used Rendered as a component. Called through a function returned by the hook.
Example Link to /courses navigate('/courses')

Use Link when users should click a navigation link. Use useNavigate when a navigation decision should happen in response to application logic.

9. Common Mistakes

Mistake 1: Calling the hook inside an event handler

// Incorrect
function Home() {
    function openCourses() {
        const navigate = useNavigate();
        navigate('/courses');
    }

    return <button onClick={openCourses}>Courses</button>;
}

Call useNavigate at the top level of the component instead.

// Correct
function Home() {
    const navigate = useNavigate();

    function openCourses() {
        navigate('/courses');
    }

    return <button onClick={openCourses}>Courses</button>;
}

Mistake 2: Using an undefined destination route

Verify that the destination path is configured in your Routes component.

Mistake 3: Navigating before an operation succeeds

When submitting a form or authenticating a user, wait for the required operation to succeed before redirecting.

Mistake 4: Forgetting the router provider

Components using useNavigate must be rendered inside the appropriate router provider.

Practice Tasks

  1. Create a button that navigates from Home to Courses.
  2. Create a form that navigates to a confirmation route after valid input.
  3. Build a simplified login example that redirects to Dashboard after success.
  4. Create Go Back and Go Forward buttons using navigate(-1) and navigate(1).
  5. Pass a course name through navigation state.
  6. Read the navigation state using useLocation.
  7. Explain the difference between Link and useNavigate.
  8. Correct an example that calls useNavigate inside an event handler.

Summary

The useNavigate hook returns a function for programmatic navigation in React Router. It is useful when a route change should happen after a button click, successful form submission, or completed application action. It also supports history navigation with numeric arguments, replacement of the current history entry, and passing temporary navigation state. Call useNavigate at the top level of your component and use the returned function inside event handlers. In the next lesson, we will learn URL parameters and the useParams hook.