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:

1// Simple React component
2function WelcomePanel() {
3  const [userName, setUserName] = React.useState("Citizen");
4
5  return (
6    <div className="quantum-panel">
7      <h2>Welcome, {userName}!</h2>
8      <p>Quantum Metropolis Terminal at your service.</p>
9      <button onClick={() => setUserName("Administrator")}>
10        Log in
11      </button>
12    </div>
13  );
14}

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.

1// app/dashboard/page.tsx - Server Component
2export default async function DashboardPage() {
3  // This code runs ONLY on the server
4  const dashboardData = await fetchDashboardData();
5
6  return (
7    <main className="quantum-dashboard">
8      <h1>Quantum Metropolis Control Panel</h1>
9      <StatusPanel data={dashboardData.status} />
10      <InteractiveControls /> {/* This will be a client component */}
11    </main>
12  );
13}
1// app/dashboard/interactive-controls.tsx - Client Component
2"use client"; // This directive marks a client component
3
4import { useState } from 'react';
5
6export default function InteractiveControls() {
7  // This code runs in the user's browser
8  const [activeSystem, setActiveSystem] = useState('energy');
9
10  return (
11    <div className="control-panel">
12      <h2>System: {activeSystem}</h2>
13      <button onClick={() => setActiveSystem('transport')}>
14        Transport
15      </button>
16      <button onClick={() => setActiveSystem('energy')}>
17        Energy
18      </button>
19      <button onClick={() => setActiveSystem('security')}>
20        Security
21      </button>
22    </div>
23  );
24}

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:

1app/                  # Main application directory
2β”œβ”€β”€ layout.tsx        # Main application layout
3β”œβ”€β”€ page.tsx          # Home page
4β”œβ”€β”€ globals.css       # Global styles
5β”œβ”€β”€ dashboard/        # Route /dashboard
6β”‚   β”œβ”€β”€ layout.tsx    # Layout for the entire dashboard section
7β”‚   β”œβ”€β”€ page.tsx      # Page /dashboard
8β”‚   └── analytics/    # Route /dashboard/analytics
9β”‚       └── page.tsx  # Page /dashboard/analytics
10β”œβ”€β”€ auth/             # Route /auth
11β”‚   β”œβ”€β”€ login/        # Route /auth/login
12β”‚   β”‚   └── page.tsx  # Page /auth/login
13β”‚   └── register/     # Route /auth/register
14β”‚       └── page.tsx  # Page /auth/register
15└── api/              # API Routes
16    └── status/       # Endpoint /api/status
17        └── 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
1// React and Next.js - Metropolis Quantum
2import React, { useState, useEffect } from 'react';
3import './App.css';
4
5console.log("Welcome to Metropolis Quantum!");
6console.log("Learning React and Next.js - the future of web development\n");
7
8// ===========================================
9// 1. React Components - Fundamentals
10// ===========================================
11console.log("=== 1. REACT COMPONENTS ===");
12
13// Functional React component
14const QuantumButton: React.FC<{
15  children: React.ReactNode;
16  onClick: () => void;
17  variant?: 'primary' | 'secondary' | 'quantum';
18}> = ({ children, onClick, variant = 'primary' }) => {
19  const [isActivated, setIsActivated] = useState(false);
20
21  const handleClick = () => {
22    setIsActivated(true);
23    onClick();
24    setTimeout(() => setIsActivated(false), 300);
25  };
26
27  return (
28    <button
29      className={`quantum-btn quantum-btn--${variant} ${isActivated ? 'activated' : ''}`}
30      onClick={handleClick}
31    >
32      {children}
33      {isActivated && <span className="quantum-ripple"></span>}
34    </button>
35  );
36};
37
38// Component with useState Hook
39const QuantumCounter: React.FC = () => {
40  const [energy, setEnergy] = useState(0);
41  const [isCharging, setIsCharging] = useState(false);
42
43  const generateEnergy = () => {
44    setIsCharging(true);
45
46    const interval = setInterval(() => {
47      setEnergy(prev => {
48        const newEnergy = prev + Math.floor(Math.random() * 10) + 1;
49        if (newEnergy >= 100) {
50          clearInterval(interval);
51          setIsCharging(false);
52          console.log("Quantum battery fully charged!");
53          return 100;
54        }
55        return newEnergy;
56      });
57    }, 200);
58  };
59
60  const resetEnergy = () => {
61    setEnergy(0);
62    setIsCharging(false);
63    console.log("Quantum battery reset");
64  };
65
66  return (
67    <div className="quantum-counter">
68      <h3>Quantum Energy Generator</h3>
69      <div className="energy-display">
70        <div className="energy-bar">
71          <div
72            className="energy-fill"
73            style={{ width: `${energy}%` }}
74          ></div>
75        </div>
76        <span className="energy-text">{energy}% Energy</span>
77      </div>
78
79      <div className="counter-controls">
80        <QuantumButton
81          onClick={generateEnergy}
82          variant="quantum"
83          disabled={isCharging}
84        >
85          {isCharging ? 'Charging...' : 'Generate Energy'}
86        </QuantumButton>
87
88        <QuantumButton
89          onClick={resetEnergy}
90          variant="secondary"
91        >
92          Reset
93        </QuantumButton>
94      </div>
95
96      {energy === 100 && (
97        <div className="achievement">
98          Achievement unlocked: Quantum Master!
99        </div>
100      )}
101    </div>
102  );
103};
104
105// ===========================================
106// 2. useEffect Hook - Side Effects
107// ===========================================
108console.log("=== 2. USE EFFECT HOOK ===");
109
110const QuantumClock: React.FC = () => {
111  const [currentTime, setCurrentTime] = useState(new Date());
112  const [quantumTime, setQuantumTime] = useState(0);
113
114  // useEffect for time updates
115  useEffect(() => {
116    console.log("Quantum Clock activated");
117
118    const timer = setInterval(() => {
119      setCurrentTime(new Date());
120      setQuantumTime(prev => prev + 1);
121    }, 1000);
122
123    // Cleanup function
124    return () => {
125      clearInterval(timer);
126      console.log("Quantum Clock deactivated");
127    };
128  }, []); // Empty dependency array - runs once
129
130  // useEffect with dependency
131  useEffect(() => {
132    if (quantumTime > 0 && quantumTime % 10 === 0) {
133      console.log(`Quantum time checkpoint: ${quantumTime} seconds`);
134    }
135  }, [quantumTime]); // Runs when quantumTime changes
136
137  const formatTime = (date: Date) => {
138    return date.toLocaleTimeString('en-US');
139  };
140
141  return (
142    <div className="quantum-clock">
143      <h3>Quantum Time Portal</h3>
144      <div className="time-display">
145        <div className="real-time">
146          <span className="time-label">Earth Time:</span>
147          <span className="time-value">{formatTime(currentTime)}</span>
148        </div>
149        <div className="quantum-time">
150          <span className="time-label">Quantum Time:</span>
151          <span className="time-value">{quantumTime}s</span>
152        </div>
153      </div>
154    </div>
155  );
156};
157
158// ===========================================
159// 3. React vs Traditional DOM
160// ===========================================
161console.log("=== 3. REACT VS TRADITIONAL DOM ===");
162
163const DOMComparison: React.FC = () => {
164  const [items, setItems] = useState<string[]>(['Quantum Core', 'Energy Shield', 'Plasma Drive']);
165  const [newItem, setNewItem] = useState('');
166
167  // React way - declarative
168  const addItemReact = () => {
169    if (newItem.trim()) {
170      setItems(prev => [...prev, newItem.trim()]);
171      setNewItem('');
172      console.log(`React way: Added "${newItem}" to quantum inventory`);
173    }
174  };
175
176  // Traditional DOM way (for comparison)
177  const addItemTraditional = () => {
178    console.log("Traditional DOM way (not recommended in React):");
179    console.log("  1. document.getElementById('list')");
180    console.log("  2. createElement('li')");
181    console.log("  3. appendChild(listItem)");
182    console.log("  4. Manual event listener management");
183    console.log("  5. Manual state synchronization");
184  };
185
186  return (
187    <div className="dom-comparison">
188      <h3>React vs Traditional DOM</h3>
189
190      <div className="react-way">
191        <h4>React Way (Declarative)</h4>
192        <div className="input-group">
193          <input
194            type="text"
195            value={newItem}
196            onChange={(e) => setNewItem(e.target.value)}
197            placeholder="Enter quantum component..."
198            className="quantum-input"
199          />
200          <QuantumButton onClick={addItemReact}>
201            Add to Inventory
202          </QuantumButton>
203        </div>
204
205        <div className="inventory-list">
206          <h5>Quantum Inventory:</h5>
207          <ul>
208            {items.map((item, index) => (
209              <li key={index} className="inventory-item">
210                {item}
211                <button
212                  onClick={() => setItems(prev => prev.filter((_, i) => i !== index))}
213                  className="remove-btn"
214                >
215                  Γ—
216                </button>
217              </li>
218            ))}
219          </ul>
220        </div>
221      </div>
222
223      <div className="traditional-way">
224        <h4>Traditional DOM Way</h4>
225        <QuantumButton onClick={addItemTraditional} variant="secondary">
226          Show Traditional Approach
227        </QuantumButton>
228        <p className="comparison-note">
229          React handles DOM updates automatically through Virtual DOM!
230        </p>
231      </div>
232    </div>
233  );
234};
235
236// ===========================================
237// 4. Component Composition
238// ===========================================
239console.log("=== 4. COMPONENT COMPOSITION ===");
240
241interface QuantumModuleProps {
242  title: string;
243  status: 'online' | 'offline' | 'maintenance';
244  children: React.ReactNode;
245}
246
247const QuantumModule: React.FC<QuantumModuleProps> = ({ title, status, children }) => {
248  const getStatusColor = () => {
249    switch (status) {
250      case 'online': return '#4caf50';
251      case 'offline': return '#f44336';
252      case 'maintenance': return '#ff9800';
253      default: return '#999';
254    }
255  };
256
257  return (
258    <div className="quantum-module">
259      <div className="module-header">
260        <h4>{title}</h4>
261        <div
262          className={`status-indicator status-${status}`}
263          style={{ backgroundColor: getStatusColor() }}
264        >
265          {status.toUpperCase()}
266        </div>
267      </div>
268      <div className="module-content">
269        {children}
270      </div>
271    </div>
272  );
273};
274
275const MetropolisControlPanel: React.FC = () => {
276  const [systemStatus, setSystemStatus] = useState<'online' | 'offline' | 'maintenance'>('online');
277
278  const toggleSystem = () => {
279    setSystemStatus(prev => {
280      const statuses: Array<'online' | 'offline' | 'maintenance'> = ['online', 'maintenance', 'offline'];
281      const currentIndex = statuses.indexOf(prev);
282      const nextStatus = statuses[(currentIndex + 1) % statuses.length];
283      console.log(`System status changed: ${prev} β†’ ${nextStatus}`);
284      return nextStatus;
285    });
286  };
287
288  return (
289    <div className="control-panel">
290      <h3>Metropolis Control Panel</h3>
291
292      <QuantumModule title="Propulsion System" status={systemStatus}>
293        <p>Quantum drive engines operating at optimal efficiency</p>
294        <div className="metric">
295          <span>Speed: </span>
296          <span className="value">
297            {systemStatus === 'online' ? '299,792,458 m/s' : 'OFFLINE'}
298          </span>
299        </div>
300      </QuantumModule>
301
302      <QuantumModule title="Defense Grid" status={systemStatus}>
303        <p>Energy shields protecting the metropolis</p>
304        <div className="metric">
305          <span>Shield Power: </span>
306          <span className="value">
307            {systemStatus === 'online' ? '98.7%' : 'OFFLINE'}
308          </span>
309        </div>
310      </QuantumModule>
311
312      <QuantumModule title="Communication Hub" status={systemStatus}>
313        <p>Quantum entanglement communication network</p>
314        <div className="metric">
315          <span>Signal Strength: </span>
316          <span className="value">
317            {systemStatus === 'online' ? 'Excellent' : 'OFFLINE'}
318          </span>
319        </div>
320      </QuantumModule>
321
322      <div className="panel-controls">
323        <QuantumButton onClick={toggleSystem} variant="quantum">
324          Toggle System Status
325        </QuantumButton>
326      </div>
327    </div>
328  );
329};
330
331// ===========================================
332// 5. Next.js Preview
333// ===========================================
334console.log("=== 5. NEXT.JS PREVIEW ===");
335
336const NextJSPreview: React.FC = () => {
337  const [currentFeature, setCurrentFeature] = useState(0);
338
339  const nextjsFeatures = [
340    {
341      title: "App Router",
342      description: "File-based routing system with layouts and nested routing",
343      code: `app/
344β”œβ”€β”€ layout.tsx        // Root layout
345β”œβ”€β”€ page.tsx         // Home page
346β”œβ”€β”€ dashboard/
347β”‚   β”œβ”€β”€ layout.tsx   // Dashboard layout
348β”‚   └── page.tsx     // Dashboard page
349└── api/
350    └── route.ts     // API endpoint`
351    },
352    {
353      title: "Server Components",
354      description: "Rendering components on the server for better performance",
355      code: `// app/quantum/page.tsx
356async function QuantumPage() {
357  // This runs on the server!
358  const data = await fetch('https://api.quantum.com/data');
359  const quantumData = await data.json();
360
361  return <div>{quantumData.energy}</div>;
362}`
363    },
364    {
365      title: "Rendering Strategies",
366      description: "SSR, SSG, ISR - choose the best strategy for your application",
367      code: `// Static Site Generation
368export async function generateStaticParams() {
369  return [{ id: '1' }, { id: '2' }];
370}
371
372// Server Side Rendering
373async function DynamicPage() {
374  const data = await fetch(url, { cache: 'no-store' });
375  return <div>{data}</div>;
376}`
377    },
378    {
379      title: "Built-in Optimizations",
380      description: "Automatic code splitting, image optimization, font optimization",
381      code: `import Image from 'next/image';
382import { Inter } from 'next/font/google';
383
384const inter = Inter({ subsets: ['latin'] });
385
386export default function Page() {
387  return (
388    <div className={inter.className}>
389      <Image
390        src="/quantum.jpg"
391        alt="Quantum City"
392        width={800}
393        height={600}
394        priority
395      />
396    </div>
397  );
398}`
399    }
400  ];
401
402  const nextFeature = () => {
403    setCurrentFeature(prev => (prev + 1) % nextjsFeatures.length);
404  };
405
406  const prevFeature = () => {
407    setCurrentFeature(prev => (prev - 1 + nextjsFeatures.length) % nextjsFeatures.length);
408  };
409
410  const feature = nextjsFeatures[currentFeature];
411
412  return (
413    <div className="nextjs-preview">
414      <h3>Next.js 16 Features</h3>
415
416      <div className="feature-showcase">
417        <div className="feature-header">
418          <h4>{feature.title}</h4>
419          <p>{feature.description}</p>
420        </div>
421
422        <div className="feature-code">
423          <pre><code>{feature.code}</code></pre>
424        </div>
425
426        <div className="feature-navigation">
427          <QuantumButton onClick={prevFeature} variant="secondary">
428            Previous
429          </QuantumButton>
430
431          <span className="feature-counter">
432            {currentFeature + 1} / {nextjsFeatures.length}
433          </span>
434
435          <QuantumButton onClick={nextFeature} variant="secondary">
436            Next
437          </QuantumButton>
438        </div>
439      </div>
440    </div>
441  );
442};
443
444// ===========================================
445// 6. Main App Component
446// ===========================================
447const App: React.FC = () => {
448  const [activeSection, setActiveSection] = useState('intro');
449
450  useEffect(() => {
451    console.log("Metropolis Quantum App initialized");
452    console.log("Ready to explore React and Next.js!");
453  }, []);
454
455  const sections = {
456    intro: { title: "Introduction", component: () => (
457      <div className="intro-section">
458        <h2>Welcome to Metropolis Quantum!</h2>
459        <p>
460          In the futuristic city of Metropolis Quantum, where technology meets magic,
461          we learn the fundamentals of React and Next.js - tools that allow building
462          interaktywne aplikacje webowe nowej generacji.
463        </p>
464        <div className="intro-features">
465          <div className="feature-card">
466            <h4>React</h4>
467            <p>Library for building user interfaces</p>
468          </div>
469          <div className="feature-card">
470            <h4>Next.js</h4>
471            <p>React framework with additional capabilities</p>
472          </div>
473          <div className="feature-card">
474            <h4>TypeScript</h4>
475            <p>Static typing for greater safety</p>
476          </div>
477        </div>
478      </div>
479    )},
480    components: { title: "Components", component: () => <QuantumCounter /> },
481    hooks: { title: "Hooks", component: () => <QuantumClock /> },
482    comparison: { title: "DOM Comparison", component: () => <DOMComparison /> },
483    composition: { title: "Composition", component: () => <MetropolisControlPanel /> },
484    nextjs: { title: "Next.js", component: () => <NextJSPreview /> }
485  };
486
487  return (
488    <div className="metropolis-app">
489      <header className="app-header">
490        <h1>Metropolis Quantum</h1>
491        <p>React & Next.js Learning Platform</p>
492      </header>
493
494      <nav className="app-navigation">
495        {Object.entries(sections).map(([key, section]) => (
496          <QuantumButton
497            key={key}
498            onClick={() => setActiveSection(key)}
499            variant={activeSection === key ? 'quantum' : 'secondary'}
500          >
501            {section.title}
502          </QuantumButton>
503        ))}
504      </nav>
505
506      <main className="app-content">
507        <div className="content-container">
508          {sections[activeSection as keyof typeof sections].component()}
509        </div>
510      </main>
511
512      <footer className="app-footer">
513        <p>Powered by Quantum Technology β€’ Learn React & Next.js</p>
514      </footer>
515    </div>
516  );
517};
518
519export default App;

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

Useful articles