Table of contents

Introduction

Navigating between pages in a Next.js application is a common requirement. However, users often experience abrupt transitions that may impact user experience. To improve usability, adding a loading indicator while redirecting enhances the user experience by providing feedback during page transitions.

This blog will explore various methods to implement redirections in Next.js 14 while displaying a loading indicator.

Problem Analysis

Why a Loading Indicator is Important?

  • Abrupt Page Navigation: When users are redirected without any indication, they might be confused about whether an action took place.
  • Slow Network Conditions: If the redirected page takes time to load, the user might assume the site is broken.
  • Improved UX: A loading spinner, progress bar, or skeleton screen enhances the user experience by informing them.

Solution

We will cover different ways to implement redirects with loading indicators in Next.js 14:

  1. Using useRouter for client-side navigation
  2. Redirecting with server components
  3. Handling redirects in API routes
  4. Using next/navigation in the app directory

Each method will include a code snippet demonstrating how to implement a loading indicator.

1. Redirect Using useRouter with a Loading State (Client-side Navigation)

Example 1: Button Click Redirect with Loading Spinner

"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
export default function Home() {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const handleRedirect = () => {
    setLoading(true);
    setTimeout(() => {
      router.push("/dashboard");
    }, 2000);
  };
  return (
    <div>
      <button onClick={handleRedirect} disabled={loading}>
        {loading ? "Redirecting..." : "Go to Dashboard"}
      </button>
      {loading && <p>Loading...</p>}
    </div>
  );
}

Explanation

  • We use useRouter for programmatic navigation.
  • The loading state is set to true before redirection, showing a spinner or message.

After a delay, router.push(“/dashboard”) executes the navigation.

2. Redirect Using Server Components (Server-side Navigation)

Example 2: Redirect Using redirect in Server Components

import { redirect } from "next/navigation";
export default function Page() {
  redirect("/dashboard");
  return null;
}

Explanation

  • The redirect() function from next/navigation performs an instant server-side redirect.
  • This method is useful when you don’t need a loading indicator because the redirect happens before rendering the page.

3. Redirect Using API Routes with a Loading Indicator

Example 3: API-Based Redirect Handling

"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
export default function ProtectedPage() {
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    fetch("/api/check-auth")
      .then((res) => res.json())
      .then((data) => {
        if (!data.authenticated) {
          router.push("/login");
        } else {
          setLoading(false);
        }
      });
  }, []);
  if (loading) {
    return <p>Checking authentication...</p>;
  }
  return

Explanation

  • Calls an API to check authentication status.
  • Shows a loading message while fetching data.
  • Redirects to the login page if authentication fails.

4. Using next/navigation in the App Directory (App Router)

Example 4: Using usePathname and useSearchParams

"use client";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
export default function Page() {
  const router = useRouter();
  useEffect(() => {
    router.replace("/new-page");
  }, []);
  return <p>Redirecting...</p>;
}

Explanation

  • Automatically replaces the URL in the browser history.
  • Displays a message while redirecting.

Key Benefits

For Developers

  • Seamless Redirection: Improves UX by showing loading indicators before redirection.
  • Flexible Implementations: Can be used in different scenarios (client-side, server-side, API routes).

For Users

  • Better Feedback: Avoids confusion by showing loading messages.
  • Enhanced Performance: Ensures smooth transitions between pages.

Conclusion

  • Implementing a loading indicator during redirects improves user experience.
  • Different approaches exist for handling redirections in Next.js 14, each with trade-offs.
  • Choose the right method based on your app’s requirements.

React Native
Bharatsinh Raj
Bharatsinh Raj

Software Engineer

Launch your MVP in 3 months!
arrow curve animation Help me succeed img
Hire Dedicated Developers or Team
arrow curve animation Help me succeed img
Flexible Pricing
arrow curve animation Help me succeed img
Tech Question's?
arrow curve animation
creole stuidos round ring waving Hand
cta

Book a call with our experts

Discussing a project or an idea with us is easy.

client-review
client-review
client-review
client-review
client-review
client-review

tech-smiley Love we get from the world

white heart