ReactJS-The Beginner Master Class
  • React In the Beginning
    • Lesson 1 - Demo: Build a Simple React App - Fast
    • Lesson 2 - HTML Review
    • Lesson 3 - CSS Review
    • Lesson 4 - Modern JavaScript (JSX) Patterns
    • Lesson 5 - Set up Dev Environment
    • Hands-on Practice
  • React Fundamentals
    • Lesson 1 - Understanding Old vs New Way of Building Web Apps - SPAs
    • Lesson 2 - Motivation for Using React as the Solution to Vanilla JS
    • Lesson 3 - What is ReactJS - How it Works
    • React Code Along from Scratch
    • Lesson 4 - Create and Run a React Project with Vite - Full Overview
    • Lesson 5 - Create Hook by State Management in React
    • Lesson 6 - React Project File and Folder Walkthrough
    • Lesson 7 - JSX and How React Treats the DOM & JSX Compilation(by Babeljs) - Overview
    • Lesson 8 - Understanding the Main Files - App.jsx and main.jsx
    • Lesson 9 - Props and One-Way Data Flow - Overview
    • Lesson 10 - Google Bookshelf App - Ver 1.0
    • Hands-on Practice I
    • Hands-on Practice II
  • React State and Styling
    • Lesson 1 - Pulling Book Data from a Different Data File
    • Lesson 2 - Overview of How State Works in React
    • Lesson 3 - RandomQuote App
    • Lesson 4 - Lifting State Up - React Pattern Overview
    • Hands-On - Simple Counter
  • Forms and Interactivity - Grocery List App
    • Lesson 1 - Setup a Simple Form and Input
    • Lesson 2 - Build Form Profile App Using Multi-input Form Data
    • Hands-on : Build a Grocery List App
  • Connecting to the Backend - Consuming APIs - UseEffect Hook
    • Lesson 1 - Connecting to the Back End - Understanding Side Effects, Hooks and useEffect - Overview
    • Lesson 2 - Fetching Data from the Backend the Right Way with useEffect Hook
    • Lesson 3 - Setting Up Loading State
    • Hands-on :Use Dependency Array and Adding Values that Control Side Effects
  • Solo Project 1
  • RESTful APIs :Build a BookSearch App -Ver 2.0
    • Lesson 1: Build and test RESTful APIs with Postman
    • Lesson 2 - BookShelf App Structure
    • Lesson 3 - Create NavBar.jsx Component
    • Lesson 4 - Create Footer Component
    • Lesson 5 - Create BookList.jsx Component
    • Lesson 6 - Create BookCard.jsx Component
    • Lesson 7 - Creating Custom Hooks - useBooks and api-client
    • Lesson 8 - Controlling Network Activities in React with AbortController
    • Lesson 9 - Show Book Details in a Modal - Working
    • Lesson 10 - Bookshelf App Summary
  • Multi-Page Applications (MPAs)
    • Build a Multi-Page React Application
    • Multi-Page React Application
    • Hands-on Practice
  • Backend Frameworks-NEXT.JS
    • Migrating from React to Next.js
    • Lesson 1: Key Concepts of NodeJS and Express for Backend Web Development
    • Lesson 2: How to set up a new Next.js project
    • Lesson 3: How to create Layouts and Pages
    • Hands-on Practice 1
    • Hands on Practice 2
      • New Project & Folder Structure
      • File-Based Routing
      • Server vs Client Components & Router Hooks
      • Start On The Navbar
      • Navbar Links, Dropdowns & React Icons
      • Active Links & Conditional Rendering
      • Homepage Components
      • Properties Page
      • Property Card Dynamic Data
      • Home Property Listings
      • Custom Not Found & Loading Pages
  • Git and GitHubs
    • Git Installation
    • Git Commands
    • GitHub Repository
    • Hands-on Practice
  • Database in Application
    • React Supabase CRUD
    • Hands-on: Note Taking App
  • NoSQL Database
    • Installing MongoDB Community Edition
    • System Env Path Setting
    • How to use MongoDB Shell
    • How to Connect and Use Mongosh in VS Code via MongoDB Extension
    • MongoDB Guide
  • Solo Project 2
  • Deployment and Web Hosting
    • Lesson 1. React+Vite+TS+Shadcn Project
    • Lesson 2. Deploying a React Vite App to Vercel from Vercel CLI
    • Lesson 3 Connecting to GitHub Repo and Automate Deployment
  • Solo Project 3
  • Final Term Project
    • Level 1 Team Project
    • Level 1 Team Project
    • Level 1 Team Project
    • Level 1 Team Project
    • Level 2 Team Project
    • Level 2 Team Project
    • Level 3 Team Project
    • Level 3 Team Project
Powered by GitBook
On this page
  • Server vs Client Components & Router Hooks
  • 1. Understanding Server vs. Client Components
  • 2. Converting a Component to a Client Component
  • 3. Introduction to Next.js Router Hooks
  • 4. Step-by-Step: Implementing Router Hooks in Your Application
  • 5. Recap and Best Practices
  1. Backend Frameworks-NEXT.JS
  2. Hands on Practice 2

Server vs Client Components & Router Hooks

Server vs Client Components & Router Hooks

1. Understanding Server vs. Client Components

  • Server Components (Default in Next.js):

    • Purpose: Render on the server side.

    • Usage: Ideal for data fetching, accessing backend resources (e.g., using an ORM), and rendering static content.

    • Limitations: Cannot use stateful or interactive hooks (like useState, useEffect, useParams, useRouter, useSearchParams.) or browser-only APIs (e.g., localStorage, geolocation).

  • Client Components:

    • Purpose: Render on the client side.

    • Usage: Necessary when you need interactivity—such as event listeners, state management, or using browser APIs.

    • Declaration: Add "use client" at the top of your file to mark it as a client component.

    Tip: Use server components when no interactivity is needed to reduce client-side JavaScript load, and switch to client components only when interactive behavior is required.


2. Converting a Component to a Client Component

a. Identify an Interactive Component

For example, imagine you have a page that needs to use router hooks or handle click events. This component should be converted to a client component.

b. Add the Client Directive

  1. Open the file (e.g., a page inside app/properties/[id]/page.jsx).

  2. At the very top, add the following directive:

    "use client";
  3. Now you can use interactive hooks (like state hooks, effects, and router hooks).

Note: Without the "use client" directive, attempting to use hooks such as useRouter or useState will trigger an error, because these are only allowed in client components.


3. Introduction to Next.js Router Hooks

Next.js provides several router hooks under the next/navigation module that let you handle routing dynamics efficiently. Here’s a quick overview:

a. useRouter

  • Purpose: Enables you to navigate programmatically (e.g., redirecting users).

  • Usage Example:

    import { useRouter } from 'next/navigation';
    
    export default function MyComponent() {
      "use client"; // Required for client-side hooks
    
      const router = useRouter();
    
      function goHome() {
        router.push('/');
      }
    
      return (
        <button onClick={goHome}>
          Go Home
        </button>
      );
    }

b. useParams

  • Purpose: Retrieve dynamic route parameters (e.g., /properties/[id]).

  • Usage Example:

    import { useParams } from 'next/navigation';
    
    export default function PropertyPage() {
      "use client"; // Because we're accessing dynamic routing in a client context
    
      const { id } = useParams();
    
      return (
        <div>
          <h1>Property ID: {id}</h1>
        </div>
      );
    }

c. useSearchParams

  • Purpose: Access query parameters from the URL.

  • Usage Example:

    import { useSearchParams } from 'next/navigation';
    
    export default function SearchComponent() {
      "use client"; // Must be a client component
    
      const searchParams = useSearchParams();
      const name = searchParams.get('name');
    
      return (
        <div>
          <p>Search parameter 'name' is: {name}</p>
        </div>
      );
    }

d. usePathname

  • Purpose: Obtain the current pathname from the URL.

  • Usage Example:

    import { usePathname } from 'next/navigation';
    
    export default function PathDisplay() {
      "use client";
    
      const pathname = usePathname();
    
      return (
        <div>
          <p>Current Path: {pathname}</p>
        </div>
      );
    }

4. Step-by-Step: Implementing Router Hooks in Your Application

Step 1: Create a New Client Component

  • File: app/properties/[id]/page.jsx

  • Action: Add "use client"; at the top.

Step 2: Use useRouter for Navigation

  • Implementation:

    "use client";
    
    import { useRouter } from 'next/navigation';
    
    export default function PropertyPage() {
      const router = useRouter();
    
      function goToHome() {
        router.push('/');
      }
    
      return (
        <div>
          <h1>Property Details</h1>
          <button onClick={goToHome}>Go Home</button>
        </div>
      );
    }

Step 3: Retrieve Dynamic Route Parameter with useParams

  • Implementation:

    "use client";
    
    import { useParams } from 'next/navigation';
    
    export default function PropertyPage() {
      const { id } = useParams();
    
      return (
        <div>
          <h1>Property ID: {id}</h1>
        </div>
      );
    }

Step 4: Use useSearchParams to Get Query Parameters

  • Implementation:

    "use client";
    
    import { useSearchParams } from 'next/navigation';
    
    export default function PropertyPage() {
      const searchParams = useSearchParams();
      const ref = searchParams.get('ref');
    
      return (
        <div>
          <h1>Property Page</h1>
          {ref && <p>Referral Code: {ref}</p>}
        </div>
      );
    }

Step 5: Display the Current Pathname with usePathname

  • Implementation:

    "use client";
    
    import { usePathname } from 'next/navigation';
    
    export default function PropertyPage() {
      const pathname = usePathname();
    
      return (
        <div>
          <p>Current URL: {pathname}</p>
        </div>
      );
    }

5. Recap and Best Practices

  • Server Components vs. Client Components:

    • Use server components for static rendering and secure data fetching.

    • Use client components (with "use client") when interactivity and stateful behavior are needed.

  • Router Hooks:

    • useRouter for programmatic navigation.

    • useParams for dynamic route parameters.

    • useSearchParams for accessing query parameters.

    • usePathname for retrieving the current path.

  • Practical Tip: When designing components, decide whether they need to be interactive. If so, mark them as client components; otherwise, lean on server components to optimize performance and security.

PreviousFile-Based RoutingNextStart On The Navbar

Last updated 2 months ago