Next.js course Β· Module 1: Next.js Configuration

Introduction to React and Next.js - History, Advantages, Ecosystem

6 min read Β·
In this lesson7

Welcome to Quantum Metropolis, the technological center of the year 2150, where buildings reach the sky, vehicles hover in the air, and the omnipresent quantum network connects all aspects of daily life. Technology is an integral part of society here, just as React and Next.js are fundamental components of the modern web ecosystem.

The Birth of React Technology

In the history of web technology development, React was like the first functional anti-gravity engine - it revolutionized the way we build user interfaces. Created in 2011 by a Facebook (now Meta) engineer and released as open source in 2013, React introduced a groundbreaking concept: declarative components with a virtual DOM.

React solved one of the most important problems in web application development - the complexity of updating the user interface. Instead of directly manipulating the DOM (which was costly and error-prone), React allowed developers to think in terms of state and components:

// Simple React component
function WelcomePanel() {
  const [userName, setUserName] = React.useState("Citizen");

  return (
    <div className="quantum-panel">
      <h2>Welcome, {userName}!</h2>
      <p>Quantum Metropolis Terminal at your service.</p>
      <button onClick={() => setUserName("Administrator")}>
        Log in
      </button>
    </div>
  );
}

The component above is like an intelligent control panel in Quantum Metropolis - it automatically reacts to state changes (in this case userName), without the need to manually control each interface element.

Older React code also uses class components (class Panel extends React.Component). They still work, but new components are written as functions.

Evolution to Next.js

Despite its advantages, React was only a user interface library. Developers still had to configure routing, performance optimization, server-side rendering, and many other aspects on their own.

Next.js appeared in 2016 as a framework built on top of React, providing ready-made solutions for these problems. This can be compared to the transition from an anti-gravity engine prototype to a fully functional flying vehicle in Quantum Metropolis.

Key Features of Next.js:

  1. Hybrid rendering - the ability to render both on the server (SSR), statically (SSG), and on the client side

  2. File-system based routing - creating application paths through folder structure

  3. Automatic code splitting - dividing code into smaller parts, loaded only when needed

  4. Image optimization - automatic processing and serving images in optimal formats

  5. Zero-config - works immediately after installation, with minimal configuration

  6. API Routes - creating API endpoints in the same project as the frontend

Next.js 16 and App Router

In Next.js 16 the recommended router is the App Router - a revolutionary change that arrived in Next.js 13 and brought an entirely new approach to application organization (the older Pages Router still works). This is like transitioning from traditional flying vehicles to quantum teleportation in Quantum Metropolis - a fundamental paradigm shift.

The App Router leverages the latest React 19.2 features, including React Server Components, which change the traditional web application model. Instead of treating the entire application as a client-rendered unit, the App Router allows flexible mixing of server-rendered and client-rendered components.

// app/dashboard/page.tsx - Server Component
export default async function DashboardPage() {
  // This code runs ONLY on the server
  const dashboardData = await fetchDashboardData();

  return (
    <main className="quantum-dashboard">
      <h1>Quantum Metropolis Control Panel</h1>
      <StatusPanel data={dashboardData.status} />
      <InteractiveControls /> {/* This will be a client component */}
    </main>
  );
}
// app/dashboard/interactive-controls.tsx - Client Component
"use client"; // This directive marks a client component

import { useState } from 'react';

export default function InteractiveControls() {
  // This code runs in the user's browser
  const [activeSystem, setActiveSystem] = useState('energy');

  return (
    <div className="control-panel">
      <h2>System: {activeSystem}</h2>
      <button onClick={() => setActiveSystem('transport')}>
        Transport
      </button>
      <button onClick={() => setActiveSystem('energy')}>
        Energy
      </button>
      <button onClick={() => setActiveSystem('security')}>
        Security
      </button>
    </div>
  );
}

React and Next.js Ecosystem

The React and Next.js ecosystem is like the advanced infrastructure of Quantum Metropolis - extensive, integrated, and constantly evolving. Here are the key elements of this ecosystem:

State Management Libraries:

  • Redux - comprehensive solution for complex applications
  • Zustand - lighter, simpler alternative
  • Jotai - atomic state architecture
  • React Query / SWR - server state management

Styling Libraries:

  • Tailwind CSS - utility class system
  • Styled Components / Emotion - CSS-in-JS
  • CSS Modules - built into Next.js
  • Chakra UI / MUI - ready-made UI components

Testing:

  • Jest - testing framework
  • React Testing Library - component testing
  • Cypress / Playwright - end-to-end tests

Developer Tools:

  • ESLint - static code analysis
  • Prettier - code formatting
  • TypeScript - static typing
  • Next.js DevTools - Next.js developer tools

Advantages of Using React and Next.js

Using React and Next.js in web projects brings benefits similar to those that Quantum Metropolis residents enjoy from the city's advanced infrastructure:

  1. Performance - optimizations like code splitting, prefetching, image optimization

  2. Scalability - component-based architecture makes managing large applications easier

  3. Developer experience - fast feedback loop thanks to hot reloading, clear project structure

  4. SEO - server-side rendering and static generation improve search engine indexing

  5. Ecosystem - rich selection of libraries and tools

  6. Community - huge, active community and documentation

Next.js Project Structure with App Router

In the App Router, the project structure resembles the district maps and transportation systems of Quantum Metropolis - everything has its place and purpose:

app/                  # Main application directory
β”œβ”€β”€ layout.tsx        # Main application layout
β”œβ”€β”€ page.tsx          # Home page
β”œβ”€β”€ globals.css       # Global styles
β”œβ”€β”€ dashboard/        # Route /dashboard
β”‚   β”œβ”€β”€ layout.tsx    # Layout for the entire dashboard section
β”‚   β”œβ”€β”€ page.tsx      # Page /dashboard
β”‚   └── analytics/    # Route /dashboard/analytics
β”‚       └── page.tsx  # Page /dashboard/analytics
β”œβ”€β”€ auth/             # Route /auth
β”‚   β”œβ”€β”€ login/        # Route /auth/login
β”‚   β”‚   └── page.tsx  # Page /auth/login
β”‚   └── register/     # Route /auth/register
β”‚       └── page.tsx  # Page /auth/register
└── api/              # API Routes
    └── status/       # Endpoint /api/status
        └── route.ts  # API handler for /api/status

In this structure, navigation is intuitive, and shared components are automatically reused across pages. This is a huge advantage compared to traditional React applications, where routing management could be complicated.

Summary

React and Next.js form a powerful duo in modern web application development, just as the quantum network and advanced infrastructure form the core of Quantum Metropolis operations.

React provides the component model and state management that makes building user interfaces more predictable and easier to maintain. Next.js adds structure, optimizations, and tools that transform React into a complete platform for building web applications.

As we delve into subsequent modules, you will learn practical applications of these technologies, just as by exploring Quantum Metropolis, you will discover all its advanced systems.

Code for this lesson: App.tsx
// React and Next.js - Metropolis Quantum
import React, { useState, useEffect } from 'react';
import './App.css';

console.log("Welcome to Metropolis Quantum!");
console.log("Learning React and Next.js - the future of web development\n");

// ===========================================
// 1. React Components - Fundamentals
// ===========================================
console.log("=== 1. REACT COMPONENTS ===");

// Functional React component
const QuantumButton: React.FC<{
  children: React.ReactNode;
  onClick: () => void;
  variant?: 'primary' | 'secondary' | 'quantum';
}> = ({ children, onClick, variant = 'primary' }) => {
  const [isActivated, setIsActivated] = useState(false);

  const handleClick = () => {
    setIsActivated(true);
    onClick();
    setTimeout(() => setIsActivated(false), 300);
  };

  return (
    <button
      className={`quantum-btn quantum-btn--${variant} ${isActivated ? 'activated' : ''}`}
      onClick={handleClick}
    >
      {children}
      {isActivated && <span className="quantum-ripple"></span>}
    </button>
  );
};

// Component with useState Hook
const QuantumCounter: React.FC = () => {
  const [energy, setEnergy] = useState(0);
  const [isCharging, setIsCharging] = useState(false);

  const generateEnergy = () => {
    setIsCharging(true);

    const interval = setInterval(() => {
      setEnergy(prev => {
        const newEnergy = prev + Math.floor(Math.random() * 10) + 1;
        if (newEnergy >= 100) {
          clearInterval(interval);
          setIsCharging(false);
          console.log("Quantum battery fully charged!");
          return 100;
        }
        return newEnergy;
      });
    }, 200);
  };

  const resetEnergy = () => {
    setEnergy(0);
    setIsCharging(false);
    console.log("Quantum battery reset");
  };

  return (
    <div className="quantum-counter">
      <h3>Quantum Energy Generator</h3>
      <div className="energy-display">
        <div className="energy-bar">
          <div
            className="energy-fill"
            style={{ width: `${energy}%` }}
          ></div>
        </div>
        <span className="energy-text">{energy}% Energy</span>
      </div>

      <div className="counter-controls">
        <QuantumButton
          onClick={generateEnergy}
          variant="quantum"
          disabled={isCharging}
        >
          {isCharging ? 'Charging...' : 'Generate Energy'}
        </QuantumButton>

        <QuantumButton
          onClick={resetEnergy}
          variant="secondary"
        >
          Reset
        </QuantumButton>
      </div>

      {energy === 100 && (
        <div className="achievement">
          Achievement unlocked: Quantum Master!
        </div>
      )}
    </div>
  );
};

// ===========================================
// 2. useEffect Hook - Side Effects
// ===========================================
console.log("=== 2. USE EFFECT HOOK ===");

const QuantumClock: React.FC = () => {
  const [currentTime, setCurrentTime] = useState(new Date());
  const [quantumTime, setQuantumTime] = useState(0);

  // useEffect for time updates
  useEffect(() => {
    console.log("Quantum Clock activated");

    const timer = setInterval(() => {
      setCurrentTime(new Date());
      setQuantumTime(prev => prev + 1);
    }, 1000);

    // Cleanup function
    return () => {
      clearInterval(timer);
      console.log("Quantum Clock deactivated");
    };
  }, []); // Empty dependency array - runs once

  // useEffect with dependency
  useEffect(() => {
    if (quantumTime > 0 && quantumTime % 10 === 0) {
      console.log(`Quantum time checkpoint: ${quantumTime} seconds`);
    }
  }, [quantumTime]); // Runs when quantumTime changes

  const formatTime = (date: Date) => {
    return date.toLocaleTimeString('en-US');
  };

  return (
    <div className="quantum-clock">
      <h3>Quantum Time Portal</h3>
      <div className="time-display">
        <div className="real-time">
          <span className="time-label">Earth Time:</span>
          <span className="time-value">{formatTime(currentTime)}</span>
        </div>
        <div className="quantum-time">
          <span className="time-label">Quantum Time:</span>
          <span className="time-value">{quantumTime}s</span>
        </div>
      </div>
    </div>
  );
};

// ===========================================
// 3. React vs Traditional DOM
// ===========================================
console.log("=== 3. REACT VS TRADITIONAL DOM ===");

const DOMComparison: React.FC = () => {
  const [items, setItems] = useState<string[]>(['Quantum Core', 'Energy Shield', 'Plasma Drive']);
  const [newItem, setNewItem] = useState('');

  // React way - declarative
  const addItemReact = () => {
    if (newItem.trim()) {
      setItems(prev => [...prev, newItem.trim()]);
      setNewItem('');
      console.log(`React way: Added "${newItem}" to quantum inventory`);
    }
  };

  // Traditional DOM way (for comparison)
  const addItemTraditional = () => {
    console.log("Traditional DOM way (not recommended in React):");
    console.log("  1. document.getElementById('list')");
    console.log("  2. createElement('li')");
    console.log("  3. appendChild(listItem)");
    console.log("  4. Manual event listener management");
    console.log("  5. Manual state synchronization");
  };

  return (
    <div className="dom-comparison">
      <h3>React vs Traditional DOM</h3>

      <div className="react-way">
        <h4>React Way (Declarative)</h4>
        <div className="input-group">
          <input
            type="text"
            value={newItem}
            onChange={(e) => setNewItem(e.target.value)}
            placeholder="Enter quantum component..."
            className="quantum-input"
          />
          <QuantumButton onClick={addItemReact}>
            Add to Inventory
          </QuantumButton>
        </div>

        <div className="inventory-list">
          <h5>Quantum Inventory:</h5>
          <ul>
            {items.map((item, index) => (
              <li key={index} className="inventory-item">
                {item}
                <button
                  onClick={() => setItems(prev => prev.filter((_, i) => i !== index))}
                  className="remove-btn"
                >
                  Γ—
                </button>
              </li>
            ))}
          </ul>
        </div>
      </div>

      <div className="traditional-way">
        <h4>Traditional DOM Way</h4>
        <QuantumButton onClick={addItemTraditional} variant="secondary">
          Show Traditional Approach
        </QuantumButton>
        <p className="comparison-note">
          React handles DOM updates automatically through Virtual DOM!
        </p>
      </div>
    </div>
  );
};

// ===========================================
// 4. Component Composition
// ===========================================
console.log("=== 4. COMPONENT COMPOSITION ===");

interface QuantumModuleProps {
  title: string;
  status: 'online' | 'offline' | 'maintenance';
  children: React.ReactNode;
}

const QuantumModule: React.FC<QuantumModuleProps> = ({ title, status, children }) => {
  const getStatusColor = () => {
    switch (status) {
      case 'online': return '#4caf50';
      case 'offline': return '#f44336';
      case 'maintenance': return '#ff9800';
      default: return '#999';
    }
  };

  return (
    <div className="quantum-module">
      <div className="module-header">
        <h4>{title}</h4>
        <div
          className={`status-indicator status-${status}`}
          style={{ backgroundColor: getStatusColor() }}
        >
          {status.toUpperCase()}
        </div>
      </div>
      <div className="module-content">
        {children}
      </div>
    </div>
  );
};

const MetropolisControlPanel: React.FC = () => {
  const [systemStatus, setSystemStatus] = useState<'online' | 'offline' | 'maintenance'>('online');

  const toggleSystem = () => {
    setSystemStatus(prev => {
      const statuses: Array<'online' | 'offline' | 'maintenance'> = ['online', 'maintenance', 'offline'];
      const currentIndex = statuses.indexOf(prev);
      const nextStatus = statuses[(currentIndex + 1) % statuses.length];
      console.log(`System status changed: ${prev} β†’ ${nextStatus}`);
      return nextStatus;
    });
  };

  return (
    <div className="control-panel">
      <h3>Metropolis Control Panel</h3>

      <QuantumModule title="Propulsion System" status={systemStatus}>
        <p>Quantum drive engines operating at optimal efficiency</p>
        <div className="metric">
          <span>Speed: </span>
          <span className="value">
            {systemStatus === 'online' ? '299,792,458 m/s' : 'OFFLINE'}
          </span>
        </div>
      </QuantumModule>

      <QuantumModule title="Defense Grid" status={systemStatus}>
        <p>Energy shields protecting the metropolis</p>
        <div className="metric">
          <span>Shield Power: </span>
          <span className="value">
            {systemStatus === 'online' ? '98.7%' : 'OFFLINE'}
          </span>
        </div>
      </QuantumModule>

      <QuantumModule title="Communication Hub" status={systemStatus}>
        <p>Quantum entanglement communication network</p>
        <div className="metric">
          <span>Signal Strength: </span>
          <span className="value">
            {systemStatus === 'online' ? 'Excellent' : 'OFFLINE'}
          </span>
        </div>
      </QuantumModule>

      <div className="panel-controls">
        <QuantumButton onClick={toggleSystem} variant="quantum">
          Toggle System Status
        </QuantumButton>
      </div>
    </div>
  );
};

// ===========================================
// 5. Next.js Preview
// ===========================================
console.log("=== 5. NEXT.JS PREVIEW ===");

const NextJSPreview: React.FC = () => {
  const [currentFeature, setCurrentFeature] = useState(0);

  const nextjsFeatures = [
    {
      title: "App Router",
      description: "File-based routing system with layouts and nested routing",
      code: `app/
β”œβ”€β”€ layout.tsx        // Root layout
β”œβ”€β”€ page.tsx         // Home page
β”œβ”€β”€ dashboard/
β”‚   β”œβ”€β”€ layout.tsx   // Dashboard layout
β”‚   └── page.tsx     // Dashboard page
└── api/
    └── route.ts     // API endpoint`
    },
    {
      title: "Server Components",
      description: "Rendering components on the server for better performance",
      code: `// app/quantum/page.tsx
async function QuantumPage() {
  // This runs on the server!
  const data = await fetch('https://api.quantum.com/data');
  const quantumData = await data.json();

  return <div>{quantumData.energy}</div>;
}`
    },
    {
      title: "Rendering Strategies",
      description: "SSR, SSG, ISR - choose the best strategy for your application",
      code: `// Static Site Generation
export async function generateStaticParams() {
  return [{ id: '1' }, { id: '2' }];
}

// Server Side Rendering
async function DynamicPage() {
  const data = await fetch(url, { cache: 'no-store' });
  return <div>{data}</div>;
}`
    },
    {
      title: "Built-in Optimizations",
      description: "Automatic code splitting, image optimization, font optimization",
      code: `import Image from 'next/image';
import { Inter } from 'next/font/google';

const inter = Inter({ subsets: ['latin'] });

export default function Page() {
  return (
    <div className={inter.className}>
      <Image
        src="/quantum.jpg"
        alt="Quantum City"
        width={800}
        height={600}
        priority
      />
    </div>
  );
}`
    }
  ];

  const nextFeature = () => {
    setCurrentFeature(prev => (prev + 1) % nextjsFeatures.length);
  };

  const prevFeature = () => {
    setCurrentFeature(prev => (prev - 1 + nextjsFeatures.length) % nextjsFeatures.length);
  };

  const feature = nextjsFeatures[currentFeature];

  return (
    <div className="nextjs-preview">
      <h3>Next.js 16 Features</h3>

      <div className="feature-showcase">
        <div className="feature-header">
          <h4>{feature.title}</h4>
          <p>{feature.description}</p>
        </div>

        <div className="feature-code">
          <pre><code>{feature.code}</code></pre>
        </div>

        <div className="feature-navigation">
          <QuantumButton onClick={prevFeature} variant="secondary">
            Previous
          </QuantumButton>

          <span className="feature-counter">
            {currentFeature + 1} / {nextjsFeatures.length}
          </span>

          <QuantumButton onClick={nextFeature} variant="secondary">
            Next
          </QuantumButton>
        </div>
      </div>
    </div>
  );
};

// ===========================================
// 6. Main App Component
// ===========================================
const App: React.FC = () => {
  const [activeSection, setActiveSection] = useState('intro');

  useEffect(() => {
    console.log("Metropolis Quantum App initialized");
    console.log("Ready to explore React and Next.js!");
  }, []);

  const sections = {
    intro: { title: "Introduction", component: () => (
      <div className="intro-section">
        <h2>Welcome to Metropolis Quantum!</h2>
        <p>
          In the futuristic city of Metropolis Quantum, where technology meets magic,
          we learn the fundamentals of React and Next.js - tools that allow building
          next-generation interactive web applications.
        </p>
        <div className="intro-features">
          <div className="feature-card">
            <h4>React</h4>
            <p>Library for building user interfaces</p>
          </div>
          <div className="feature-card">
            <h4>Next.js</h4>
            <p>React framework with additional capabilities</p>
          </div>
          <div className="feature-card">
            <h4>TypeScript</h4>
            <p>Static typing for greater safety</p>
          </div>
        </div>
      </div>
    )},
    components: { title: "Components", component: () => <QuantumCounter /> },
    hooks: { title: "Hooks", component: () => <QuantumClock /> },
    comparison: { title: "DOM Comparison", component: () => <DOMComparison /> },
    composition: { title: "Composition", component: () => <MetropolisControlPanel /> },
    nextjs: { title: "Next.js", component: () => <NextJSPreview /> }
  };

  return (
    <div className="metropolis-app">
      <header className="app-header">
        <h1>Metropolis Quantum</h1>
        <p>React & Next.js Learning Platform</p>
      </header>

      <nav className="app-navigation">
        {Object.entries(sections).map(([key, section]) => (
          <QuantumButton
            key={key}
            onClick={() => setActiveSection(key)}
            variant={activeSection === key ? 'quantum' : 'secondary'}
          >
            {section.title}
          </QuantumButton>
        ))}
      </nav>

      <main className="app-content">
        <div className="content-container">
          {sections[activeSection as keyof typeof sections].component()}
        </div>
      </main>

      <footer className="app-footer">
        <p>Powered by Quantum Technology β€’ Learn React & Next.js</p>
      </footer>
    </div>
  );
};

export default App;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. In which year was React released to the public as open source?

  2. 2. React was created by:

  3. 3. The main advantage of React is:

Hands-on tasks in the game

  • Code editor

    Create a functional component called HelloWorld that returns an <h1> heading with a welcome message, e.g. "Welcome to Metropolis Quantum!".

  • Click in order

    Arrange the declaration of a functional component in React

  1. QuestionThe Year React Was Open-Sourced
  2. QuestionCreator of React
  3. Coding taskPractice: HelloWorld Component
  4. QuestionMain Advantage of React
  5. Click in orderFunctional Component Declaration

Useful articles