DEV Community

Cover image for The Ultimate Complete Frontend Development Guide 2026
Akhilesh
Akhilesh

Posted on

The Ultimate Complete Frontend Development Guide 2026

Table of Contents

1. HTML5 Complete Guide

What is HTML5?
HTML5 (HyperText Markup Language version 5) is the latest standard for structuring and presenting content on the World Wide Web. It introduces semantic elements, multimedia support, and powerful APIs for building modern web applications.

Definition: HTML5 is a markup language used for structuring and presenting content on the web, featuring semantic elements, native multimedia support, and canvas/SVG graphics.
Basic HTML5 Document Structure

<!DOCTYPE html>
<!-- Declaration: Tells browser this is HTML5 -->

<html lang="en">
<!-- Root element with language attribute for accessibility -->

<head>
    <!-- Metadata container - not visible on page -->
    <meta charset="UTF-8">
    <!-- Character encoding: UTF-8 supports all languages -->

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Responsive viewport: Makes site mobile-friendly -->

    <meta name="description" content="Complete frontend development guide">
    <!-- SEO description: Shown in search results -->

    <meta name="keywords" content="HTML, CSS, JavaScript, React">
    <!-- SEO keywords -->

    <meta name="author" content="Your Name">
    <meta name="robots" content="index, follow">
    <!-- Search engine indexing instructions -->

    <title>Complete Frontend Guide 2024-2025</title>
    <!-- Browser tab title -->

    <!-- Open Graph for social sharing -->
    <meta property="og:title" content="Frontend Guide">
    <meta property="og:description" content="Learn modern web development">
    <meta property="og:image" content="https://example.com/image.jpg">

    <!-- Favicon -->
    <link rel="icon" type="image/x-icon" href="/favicon.ico">
    <link rel="apple-touch-icon" href="/apple-touch-icon.png">

    <!-- External CSS -->
    <link rel="stylesheet" href="styles.css">

    <!-- Preconnect for performance -->
    <link rel="preconnect" href="https://fonts.googleapis.com">

    <!-- Preload critical resources -->
    <link rel="preload" href="critical.css" as="style">

    <!-- Base URL for all relative URLs -->
    <base href="https://example.com/">
</head>

<body>
    <!-- All visible content goes here -->

    <script src="app.js" defer></script>
    <!-- defer: Script executes after HTML parsing -->
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

HTML5 Semantic Elements

Definition: Semantic elements clearly describe their meaning to both the browser and the developer, improving accessibility, SEO, and code readability .

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Semantic HTML5 Example</title>
</head>
<body>

    <!-- HEADER: Introductory content or navigation -->
    <header>
        <h1>My Website</h1>
        <p>Tagline or description</p>

        <!-- NAV: Navigation links -->
        <nav aria-label="Main navigation">
            <ul>
                <li><a href="#home">Home</a></li>
                <li><a href="#about">About</a></li>
                <li><a href="#services">Services</a></li>
                <li><a href="#contact">Contact</a></li>
            </ul>
        </nav>
    </header>

    <!-- MAIN: Primary content (only one per page) -->
    <main>

        <!-- SECTION: Thematic grouping of content -->
        <section id="about" aria-labelledby="about-heading">
            <h2 id="about-heading">About Us</h2>
            <p>Company information...</p>
        </section>

        <!-- ARTICLE: Self-contained, independently distributable content -->
        <article>
            <header>
                <h2>Blog Post Title</h2>
                <p>
                    Published on <time datetime="2024-12-25">December 25, 2024</time>
                    by <span itemprop="author">John Doe</span>
                </p>
            </header>

            <p>Article content...</p>

            <figure>
                <img src="chart.jpg" alt="Sales data chart">
                <figcaption>Fig.1 - Annual Sales Growth</figcaption>
            </figure>

            <footer>
                <p>Tags: <span class="tag">HTML5</span> <span class="tag">CSS</span></p>
            </footer>
        </article>

        <!-- ASIDE: Tangentially related content (sidebar) -->
        <aside aria-label="Related articles">
            <h3>Related Posts</h3>
            <ul>
                <li><a href="#">Article 1</a></li>
                <li><a href="#">Article 2</a></li>
            </ul>
        </aside>

    </main>

    <!-- FOOTER: Footer for page or section -->
    <footer>
        <p>&copy; 2024 My Website. All rights reserved.</p>
        <address>
            Contact: <a href="mailto:info@example.com">info@example.com</a>
        </address>
    </footer>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Interactive Elements

<!-- DETAILS & SUMMARY: Collapsible content -->
<details>
    <summary>Click to expand</summary>
    <p>This content is hidden until clicked.</p>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
    </ul>
</details>

<!-- DIALOG: Modal dialog -->
<dialog id="myModal">
    <h2>Modal Title</h2>
    <p>This is a native HTML modal dialog.</p>
    <button onclick="document.getElementById('myModal').close()">Close</button>
</dialog>

<button onclick="document.getElementById('myModal').showModal()">
    Open Modal
</button>

<!-- PROGRESS & METER -->
<label>Download progress:
    <progress value="70" max="100">70%</progress>
</label>

<label>Disk usage:
    <meter value="0.7" min="0" max="1" low="0.3" high="0.8" optimum="0.5">
        70%
    </meter>
</label>

<!-- MARK: Highlighted text -->
<p>This is <mark>important</mark> information.</p>

<!-- TIME: Machine-readable dates -->
<p>Event date: <time datetime="2024-12-25T20:00:00">Christmas Day at 8pm</time></p>

<!-- OUTPUT: Calculation result -->
<form oninput="result.value = parseInt(a.value) + parseInt(b.value)">
    <input type="number" name="a" value="0"> +
    <input type="number" name="b" value="0"> =
    <output name="result" for="a b">0</output>
</form>
Enter fullscreen mode Exit fullscreen mode

HTML5 Forms & Input Types

<form action="/submit" method="POST" enctype="multipart/form-data" novalidate>

    <!-- TEXT INPUTS -->
    <label for="username">Username:</label>
    <input 
        type="text" 
        id="username" 
        name="username"
        placeholder="Enter username"
        required
        minlength="3"
        maxlength="20"
        pattern="[A-Za-z0-9_]+"
        title="Alphanumeric and underscores only"
        autocomplete="username"
    >

    <!-- EMAIL -->
    <label for="email">Email:</label>
    <input 
        type="email" 
        id="email" 
        name="email"
        placeholder="user@example.com"
        required
        multiple
        autocomplete="email"
    >

    <!-- PASSWORD -->
    <label for="password">Password:</label>
    <input 
        type="password" 
        id="password" 
        name="password"
        required
        minlength="8"
        pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
        title="Must contain at least one number, one uppercase and lowercase letter"
    >

    <!-- NUMBER -->
    <label for="age">Age:</label>
    <input 
        type="number" 
        id="age" 
        name="age"
        min="18"
        max="120"
        step="1"
        value="25"
    >

    <!-- TEL -->
    <label for="phone">Phone:</label>
    <input 
        type="tel" 
        id="phone" 
        name="phone"
        pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
        placeholder="123-456-7890"
    >

    <!-- URL -->
    <label for="website">Website:</label>
    <input 
        type="url" 
        id="website" 
        name="website"
        placeholder="https://example.com"
    >

    <!-- SEARCH -->
    <label for="search">Search:</label>
    <input 
        type="search" 
        id="search" 
        name="search"
        placeholder="Search..."
        results="5"
    >

    <!-- DATE & TIME -->
    <label for="birthday">Birthday:</label>
    <input type="date" id="birthday" name="birthday" min="1900-01-01" max="2024-12-31">

    <label for="meeting">Meeting Time:</label>
    <input type="time" id="meeting" name="meeting">

    <label for="appointment">Appointment:</label>
    <input type="datetime-local" id="appointment" name="appointment">

    <label for="month">Month:</label>
    <input type="month" id="month" name="month">

    <label for="week">Week:</label>
    <input type="week" id="week" name="week">

    <!-- COLOR -->
    <label for="color">Favorite Color:</label>
    <input type="color" id="color" name="color" value="#ff0000">

    <!-- RANGE -->
    <label for="volume">Volume:</label>
    <input 
        type="range" 
        id="volume" 
        name="volume"
        min="0"
        max="100"
        value="50"
        step="5"
    >
    <output for="volume" id="volume-output">50</output>

    <!-- FILE UPLOAD -->
    <label for="resume">Upload Resume:</label>
    <input 
        type="file" 
        id="resume" 
        name="resume"
        accept=".pdf,.doc,.docx"
        multiple
        capture="environment"
    >

    <!-- IMAGE CAPTURE -->
    <label for="photo">Take Photo:</label>
    <input 
        type="file" 
        id="photo" 
        name="photo"
        accept="image/*"
        capture="user"
    >

    <!-- HIDDEN -->
    <input type="hidden" name="csrf_token" value="random_token_here">

    <!-- CHECKBOX -->
    <fieldset>
        <legend>Interests:</legend>
        <label>
            <input type="checkbox" name="interests" value="coding" checked>
            Coding
        </label>
        <label>
            <input type="checkbox" name="interests" value="design">
            Design
        </label>
        <label>
            <input type="checkbox" name="interests" value="music">
            Music
        </label>
    </fieldset>

    <!-- RADIO BUTTONS -->
    <fieldset>
        <legend>Gender:</legend>
        <label>
            <input type="radio" name="gender" value="male" required>
            Male
        </label>
        <label>
            <input type="radio" name="gender" value="female">
            Female
        </label>
        <label>
            <input type="radio" name="gender" value="other">
            Other
        </label>
    </fieldset>

    <!-- TEXTAREA -->
    <label for="message">Message:</label>
    <textarea 
        id="message" 
        name="message"
        rows="5"
        cols="50"
        maxlength="500"
        placeholder="Enter your message..."
    ></textarea>

    <!-- SELECT DROPDOWN -->
    <label for="country">Country:</label>
    <select id="country" name="country" required>
        <option value="">Select a country</option>
        <option value="us">United States</option>
        <option value="uk">United Kingdom</option>
        <option value="ca">Canada</option>
    </select>

    <!-- SELECT WITH OPTGROUP -->
    <label for="car">Car:</label>
    <select id="car" name="car">
        <optgroup label="German Cars">
            <option value="bmw">BMW</option>
            <option value="mercedes">Mercedes</option>
            <option value="audi">Audi</option>
        </optgroup>
        <optgroup label="Japanese Cars">
            <option value="toyota">Toyota</option>
            <option value="honda">Honda</option>
        </optgroup>
    </select>

    <!-- MULTIPLE SELECT -->
    <label for="skills">Skills (hold Ctrl/Cmd to select multiple):</label>
    <select id="skills" name="skills" multiple size="5">
        <option value="html">HTML</option>
        <option value="css">CSS</option>
        <option value="js">JavaScript</option>
        <option value="react">React</option>
        <option value="node">Node.js</option>
    </select>

    <!-- DATALIST (Autocomplete) -->
    <label for="browser">Browser:</label>
    <input list="browsers" id="browser" name="browser" placeholder="Type to search...">
    <datalist id="browsers">
        <option value="Chrome">
        <option value="Firefox">
        <option value="Safari">
        <option value="Edge">
        <option value="Opera">
    </datalist>

    <!-- BUTTONS -->
    <button type="submit">Submit</button>
    <button type="reset">Reset</button>
    <button type="button" onclick="alert('Hello!')">Click Me</button>

    <!-- FIELDSET & LEGEND -->
    <fieldset disabled>
        <legend>Disabled Section</legend>
        <input type="text" placeholder="This is disabled">
    </fieldset>

</form>
Enter fullscreen mode Exit fullscreen mode

HTML5 Multimedia

<!-- AUDIO -->
<audio controls preload="metadata" loop muted>
    <source src="music.mp3" type="audio/mpeg">
    <source src="music.ogg" type="audio/ogg">
    <track kind="captions" src="captions.vtt" srclang="en" label="English">
    Your browser does not support the audio element.
</audio>

<!-- VIDEO -->
<video width="640" height="360" controls poster="thumbnail.jpg" preload="auto">
    <source src="movie.mp4" type="video/mp4">
    <source src="movie.webm" type="video/webm">
    <track kind="subtitles" src="subtitles_en.vtt" srclang="en" label="English" default>
    <track kind="subtitles" src="subtitles_es.vtt" srclang="es" label="Spanish">
    Your browser does not support the video tag.
</video>

<!-- CANVAS -->
<canvas id="myCanvas" width="500" height="300">
    Your browser does not support the canvas element.
</canvas>

<script>
    const canvas = document.getElementById('myCanvas');
    const ctx = canvas.getContext('2d');
    ctx.fillStyle = 'blue';
    ctx.fillRect(10, 10, 100, 100);
</script>

<!-- SVG -->
<svg width="100" height="100" viewBox="0 0 100 100">
    <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
    <text x="50" y="55" text-anchor="middle" fill="white" font-size="20">SVG</text>
</svg>

<!-- PICTURE (Responsive Images) -->
<picture>
    <source media="(min-width: 1200px)" srcset="large.jpg" type="image/jpeg">
    <source media="(min-width: 768px)" srcset="medium.jpg" type="image/jpeg">
    <source srcset="small.jpg" type="image/jpeg">
    <img src="fallback.jpg" alt="Responsive image description" loading="lazy">
</picture>

<!-- FIGURE -->
<figure>
    <img src="chart.png" alt="Bar chart showing sales data">
    <figcaption>
        Figure 1: Quarterly sales performance for 2024. 
        Data source: Internal analytics.
    </figcaption>
</figure>
Enter fullscreen mode Exit fullscreen mode

HTML5 Tables

<table>
    <caption>Monthly Sales Report</caption>

    <colgroup>
        <col style="background-color: #f0f0f0;">
        <col span="2" style="background-color: #ffffff;">
        <col style="background-color: #e8f4f8;">
    </colgroup>

    <thead>
        <tr>
            <th scope="col">Month</th>
            <th scope="col">Product A</th>
            <th scope="col">Product B</th>
            <th scope="col">Total</th>
        </tr>
    </thead>

    <tbody>
        <tr>
            <th scope="row">January</th>
            <td>$10,000</td>
            <td>$15,000</td>
            <td>$25,000</td>
        </tr>
        <tr>
            <th scope="row">February</th>
            <td>$12,000</td>
            <td>$18,000</td>
            <td>$30,000</td>
        </tr>
    </tbody>

    <tfoot>
        <tr>
            <th scope="row">Total</th>
            <td>$22,000</td>
            <td>$33,000</td>
            <td>$55,000</td>
        </tr>
    </tfoot>
</table>

<!-- Complex Table with Spanning -->
<table>
    <thead>
        <tr>
            <th rowspan="2">Product</th>
            <th colspan="2">Q1</th>
            <th colspan="2">Q2</th>
        </tr>
        <tr>
            <th>Sales</th>
            <th>Profit</th>
            <th>Sales</th>
            <th>Profit</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Widget A</td>
            <td>100</td>
            <td>$500</td>
            <td>150</td>
            <td>$750</td>
        </tr>
    </tbody>
</table>
Enter fullscreen mode Exit fullscreen mode

HTML Character Entities

&lt;      <!-- < (less than) -->
&gt;      <!-- > (greater than) -->
&amp;     <!-- & (ampersand) -->
&quot;    <!-- " (double quote) -->
&apos;    <!-- ' (apostrophe) -->
&nbsp;    <!-- non-breaking space -->
&copy;    <!-- © (copyright) -->
&reg;     <!-- ® (registered trademark) -->
&trade;   <!-- ™ (trademark) -->
&euro;    <!-- € (euro sign) -->
&pound;   <!-- £ (pound sign) -->
&yen;     <!-- ¥ (yen sign) -->
&cent;    <!-- ¢ (cent sign) -->
&sect;    <!-- § (section sign) -->
&deg;     <!-- ° (degree symbol) -->
&times;   <!-- × (multiplication) -->
&divide;  <!-- ÷ (division) -->
&ndash;   <!-- – (en dash) -->
&mdash;   <!-- — (em dash) -->
Enter fullscreen mode Exit fullscreen mode

2. CSS3 Complete Guide

What is CSS3?

Definition: CSS3 (Cascading Style Sheets Level 3) is the latest evolution of the Cascading Style Sheets language, extending CSS2.1 with new features like rounded corners, shadows, gradients, transitions, animations, and responsive design capabilities.

CSS Syntax & Selectors

/* BASIC SYNTAX */
selector {
    property: value;
    property: value;
}

/* ELEMENT SELECTOR */
p {
    color: blue;
    font-size: 16px;
}

/* CLASS SELECTOR */
.highlight {
    background-color: yellow;
    padding: 10px;
}

/* ID SELECTOR */
#header {
    background-color: #333;
    color: white;
}

/* ATTRIBUTE SELECTORS */
input[type="text"] {
    border: 2px solid #ccc;
}

a[href^="https"] {
    color: green;  /* Starts with https */
}

a[href$=".pdf"] {
    color: red;    /* Ends with .pdf */
}

a[href*="example"] {
    color: orange; /* Contains example */
}

/* COMBINATOR SELECTORS */

/* Descendant (space) - any level deep */
article p {
    line-height: 1.6;
}

/* Child (>) - direct children only */
ul > li {
    list-style: none;
}

/* Adjacent Sibling (+) - immediately after */
h1 + p {
    font-weight: bold;
}

/* General Sibling (~) - all siblings after */
h1 ~ p {
    color: gray;
}

/* GROUPING SELECTOR */
h1, h2, h3, h4, h5, h6 {
    font-family: 'Georgia', serif;
}

/* PSEUDO-CLASSES */

/* Link states */
a:link { color: blue; }
a:visited { color: purple; }
a:hover { color: red; text-decoration: underline; }
a:active { color: orange; }

/* Form states */
input:focus {
    border-color: #4CAF50;
    outline: none;
    box-shadow: 0 0 5px rgba(76, 175, 80, 0.3);
}

input:disabled {
    background-color: #f5f5f5;
    cursor: not-allowed;
}

input:checked {
    accent-color: #4CAF50;
}

input:valid {
    border-color: green;
}

input:invalid {
    border-color: red;
}

input:required {
    border-left: 3px solid #ff9800;
}

/* Structural pseudo-classes */
li:first-child {
    font-weight: bold;
}

li:last-child {
    margin-bottom: 0;
}

li:nth-child(odd) {
    background-color: #f9f9f9;
}

li:nth-child(even) {
    background-color: white;
}

li:nth-child(3n) {
    color: blue;
}

li:nth-child(3n+1) {
    color: red;
}

p:only-child {
    font-size: 1.2em;
}

p:empty {
    display: none;
}

/* Negation pseudo-class */
p:not(.special) {
    color: black;
}

/* PSEUDO-ELEMENTS */

/* Generated content */
.quote::before {
    content: '"';
    font-size: 2em;
    color: #ccc;
}

.quote::after {
    content: '"';
    font-size: 2em;
    color: #ccc;
}

/* First letter/line */
p::first-letter {
    font-size: 3em;
    float: left;
    margin-right: 8px;
    line-height: 1;
}

p::first-line {
    font-weight: bold;
    text-transform: uppercase;
}

/* Selection styling */
::selection {
    background-color: #ffeb3b;
    color: black;
}

/* Placeholder styling */
input::placeholder {
    color: #999;
    font-style: italic;
}
Enter fullscreen mode Exit fullscreen mode

CSS Colors & Units

.element {
    /* COLOR NAMES */
    color: red;
    color: CornflowerBlue;

    /* HEXADECIMAL */
    color: #ff0000;      /* Red */
    color: #f00;         /* Short form */
    color: #ff000080;    /* With alpha (transparent red) */

    /* RGB/RGBA */
    color: rgb(255, 0, 0);
    color: rgba(255, 0, 0, 0.5);

    /* HSL/HSLA (Hue, Saturation, Lightness) */
    color: hsl(0, 100%, 50%);      /* Red */
    color: hsla(0, 100%, 50%, 0.5);

    /* HWB (Hue, Whiteness, Blackness) */
    color: hwb(0 0% 0%);           /* Red */

    /* LAB (Lightness, A-axis, B-axis) */
    color: lab(50% 20 -30);

    /* LCH (Lightness, Chroma, Hue) */
    color: lch(50% 30 180);

    /* COLOR (CSS Color Module Level 4/5) */
    color: color(display-p3 1 0 0);
    color: color-mix(in srgb, red 50%, blue 50%);

    /* CURRENT COLOR */
    border: 2px solid currentColor;

    /* TRANSPARENT */
    background-color: transparent;

    /* SYSTEM COLORS */
    color: CanvasText;
    background-color: Canvas;
}

/* CSS UNITS */
.element {
    /* ABSOLUTE UNITS */
    width: 100px;        /* Pixels */
    width: 1in;          /* Inches */
    width: 2.54cm;       /* Centimeters */
    width: 10mm;         /* Millimeters */
    width: 12pt;         /* Points (1/72 inch) */
    width: 1pc;          /* Picas (12 points) */

    /* RELATIVE UNITS */
    font-size: 1rem;     /* Root element font size */
    font-size: 1.5em;    /* Parent element font size */
    width: 50%;          /* Percentage of parent */
    width: 50vw;         /* Viewport width */
    height: 100vh;       /* Viewport height */
    width: 10vmin;       /* Smaller of vw/vh */
    width: 10vmax;       /* Larger of vw/vh */
    width: 50cqw;        /* Container query width */
    height: 50cqh;       /* Container query height */

    /* CALCULATIONS */
    width: calc(100% - 40px);
    width: calc(50vw + 20px);
    font-size: clamp(14px, 2vw, 18px);  /* Min, preferred, max */
}
Enter fullscreen mode Exit fullscreen mode

CSS Typography

.text {
    /* FONT FAMILY */
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 
                 'Helvetica Neue', Arial, sans-serif;

    /* SYSTEM FONT STACK */
    font-family: system-ui, -apple-system, sans-serif;

    /* CUSTOM FONT */
    @font-face {
        font-family: 'CustomFont';
        src: url('font.woff2') format('woff2'),
             url('font.woff') format('woff');
        font-weight: 400;
        font-style: normal;
        font-display: swap;
    }

    font-family: 'CustomFont', sans-serif;

    /* FONT SIZE */
    font-size: 16px;
    font-size: 1rem;
    font-size: 1.125rem;  /* 18px if root is 16px */

    /* FONT WEIGHT */
    font-weight: normal;   /* 400 */
    font-weight: bold;     /* 700 */
    font-weight: 100;      /* Thin */
    font-weight: 900;      /* Black */
    font-weight: 550;      /* Variable font */

    /* FONT STYLE */
    font-style: normal;
    font-style: italic;
    font-style: oblique 10deg;

    /* FONT VARIANT */
    font-variant: small-caps;
    font-variant-numeric: tabular-nums;

    /* LINE HEIGHT */
    line-height: 1.5;
    line-height: 150%;
    line-height: 24px;

    /* LETTER & WORD SPACING */
    letter-spacing: 0.05em;
    word-spacing: 0.1em;

    /* TEXT ALIGN */
    text-align: left;
    text-align: center;
    text-align: right;
    text-align: justify;

    /* TEXT DECORATION */
    text-decoration: none;
    text-decoration: underline;
    text-decoration: underline wavy red;
    text-decoration: line-through;
    text-decoration-thickness: 2px;
    text-underline-offset: 4px;

    /* TEXT TRANSFORM */
    text-transform: uppercase;
    text-transform: lowercase;
    text-transform: capitalize;
    text-transform: none;

    /* TEXT INDENT */
    text-indent: 2em;

    /* TEXT SHADOW */
    text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
    text-shadow: 0 0 10px #fff, 0 0 20px #ff00de;  /* Glow effect */

    /* WHITE SPACE */
    white-space: normal;
    white-space: nowrap;
    white-space: pre;
    white-space: pre-wrap;
    white-space: pre-line;

    /* WORD BREAK */
    word-break: normal;
    word-break: break-all;
    word-break: keep-all;
    overflow-wrap: break-word;
    hyphens: auto;

    /* TEXT OVERFLOW */
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;

    /* WRITING MODE */
    writing-mode: horizontal-tb;
    writing-mode: vertical-rl;

    /* TEXT ORIENTATION */
    text-orientation: mixed;
    text-orientation: upright;
}
Enter fullscreen mode Exit fullscreen mode

CSS Backgrounds & Borders

.element {
    /* BACKGROUND COLOR */
    background-color: #f0f0f0;
    background-color: rgba(0,0,0,0.5);

    /* BACKGROUND IMAGE */
    background-image: url('image.jpg');

    /* MULTIPLE BACKGROUNDS */
    background-image: 
        linear-gradient(to bottom, rgba(0,0,0,0.5), rgba(0,0,0,0.5)),
        url('image.jpg');

    /* BACKGROUND REPEAT */
    background-repeat: no-repeat;
    background-repeat: repeat-x;
    background-repeat: repeat-y;
    background-repeat: space;
    background-repeat: round;

    /* BACKGROUND POSITION */
    background-position: center;
    background-position: top left;
    background-position: 50% 50%;
    background-position: 20px 30px;

    /* BACKGROUND SIZE */
    background-size: cover;       /* Fill element, may crop */
    background-size: contain;     /* Fit inside, may letterbox */
    background-size: 100% 100%;  /* Stretch to fill */
    background-size: 500px auto;

    /* BACKGROUND ATTACHMENT */
    background-attachment: scroll;
    background-attachment: fixed;   /* Parallax effect */
    background-attachment: local;

    /* BACKGROUND ORIGIN & CLIP */
    background-origin: padding-box;
    background-clip: content-box;
    background-clip: text;  /* Text fill with background */
    -webkit-background-clip: text;
    color: transparent;

    /* SHORTHAND */
    background: #f0f0f0 url('img.jpg') no-repeat center center / cover;

    /* GRADIENTS */
    background: linear-gradient(to right, red, yellow);
    background: linear-gradient(45deg, red, blue);
    background: linear-gradient(to bottom, #fff 0%, #000 100%);
    background: linear-gradient(90deg, red 0%, yellow 50%, blue 100%);

    /* RADIAL GRADIENT */
    background: radial-gradient(circle, red, yellow);
    background: radial-gradient(ellipse at top, blue, green);
    background: radial-gradient(circle at 30% 30%, red, blue);

    /* CONIC GRADIENT */
    background: conic-gradient(from 45deg, red, yellow, green, blue, red);

    /* REPEATING GRADIENTS */
    background: repeating-linear-gradient(45deg, red, red 10px, blue 10px, blue 20px);

    /* BORDERS */
    border: 2px solid #333;
    border-width: 2px;
    border-style: solid;     /* solid, dashed, dotted, double, groove, ridge, inset, outset */
    border-color: #333;

    /* INDIVIDUAL SIDES */
    border-top: 3px solid red;
    border-right: 2px dashed blue;
    border-bottom: 1px dotted green;
    border-left: 4px double orange;

    /* BORDER RADIUS */
    border-radius: 10px;
    border-radius: 10px 20px;           /* top-left/bottom-right, top-right/bottom-left */
    border-radius: 10px 20px 30px 40px;  /* top-left, top-right, bottom-right, bottom-left */
    border-radius: 50%;                  /* Circle */
    border-radius: 100% 0 100% 0;        /* Organic shape */

    /* BORDER IMAGE */
    border-image: url('border.png') 30 round;
    border-image: linear-gradient(to bottom, red, blue) 1;

    /* OUTLINE (outside border) */
    outline: 3px solid #4CAF50;
    outline-offset: 5px;

    /* BOX SHADOW */
    box-shadow: 5px 5px 10px rgba(0,0,0,0.3);
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    box-shadow: 0 10px 30px rgba(0,0,0,0.3);  /* Elevation */
    box-shadow: inset 0 0 10px rgba(0,0,0,0.5);  /* Inner shadow */

    /* MULTIPLE SHADOWS */
    box-shadow:
        0 2px 4px rgba(0,0,0,0.1),
        0 4px 8px rgba(0,0,0,0.1),
        0 8px 16px rgba(0,0,0,0.1);

    /* DROP SHADOW (for transparent images) */
    filter: drop-shadow(5px 5px 10px rgba(0,0,0,0.3));
}
Enter fullscreen mode Exit fullscreen mode

3. CSS Layout & Box Model

CSS Box Model

Definition: The CSS box model is essentially a box that wraps around every HTML element. It consists of: content, padding, borders, and margins.

/* BOX MODEL VISUALIZATION */
.box {
    /* CONTENT */
    width: 300px;
    height: 200px;

    /* PADDING (inside spacing) */
    padding: 20px;                    /* All sides */
    padding: 10px 20px;               /* Vertical Horizontal */
    padding: 10px 20px 30px;          /* Top Horizontal Bottom */
    padding: 10px 20px 30px 40px;     /* Top Right Bottom Left */

    /* Individual padding */
    padding-top: 10px;
    padding-right: 20px;
    padding-bottom: 30px;
    padding-left: 40px;

    /* BORDER */
    border: 2px solid #333;
    border-width: 2px;
    border-style: solid;
    border-color: #333;

    /* MARGIN (outside spacing) */
    margin: 20px;
    margin: 10px 20px;
    margin: 10px 20px 30px 40px;

    /* Center horizontally */
    margin: 0 auto;

    /* Negative margin (overlap) */
    margin-top: -10px;

    /* BOX SIZING */
    box-sizing: content-box;  /* Width/height = content only (default) */
    box-sizing: border-box;   /* Width/height = content + padding + border */
}

/* GLOBAL BOX-SIZING RESET */
*,
*::before,
*::after {
    box-sizing: border-box;
}
Enter fullscreen mode Exit fullscreen mode

CSS Positioning

/* POSITION PROPERTY */

/* STATIC (default) */
.static {
    position: static;
}

/* RELATIVE */
.relative {
    position: relative;
    top: 10px;      /* Move down from original position */
    left: 20px;     /* Move right from original position */
    /* Still takes up original space in document flow */
}

/* ABSOLUTE */
.absolute {
    position: absolute;
    top: 0;
    right: 0;
    /* Removed from document flow */
    /* Positioned relative to nearest positioned ancestor */
    /* If no positioned ancestor, relative to body */
}

/* FIXED */
.fixed {
    position: fixed;
    top: 0;
    left: 0;
    /* Positioned relative to viewport */
    /* Stays in place when scrolling */
}

/* STICKY */
.sticky {
    position: sticky;
    top: 0;
    /* Toggles between relative and fixed */
    /* Acts like relative until scrolled to threshold */
    /* Then acts like fixed */
}

/* Z-INDEX (stacking order) */
.element {
    position: relative;
    z-index: 10;
    /* Higher value = on top */
    /* Only works with positioned elements */
}

/* COMMON PATTERNS */

/* Center absolutely positioned element */
.center-absolute {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

/* Full cover overlay */
.overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
}

/* Sticky header */
.sticky-header {
    position: sticky;
    top: 0;
    background: white;
    z-index: 100;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* Fixed chat button */
.chat-button {
    position: fixed;
    bottom: 20px;
    right: 20px;
    z-index: 1000;
}
Enter fullscreen mode Exit fullscreen mode

CSS Display & Visibility

/* DISPLAY PROPERTY */

/* BLOCK */
.block {
    display: block;
    /* Takes full width available */
    /* Starts on new line */
    /* Can set width/height */
    /* Examples: div, p, h1, section */
}

/* INLINE */
.inline {
    display: inline;
    /* Takes only necessary width */
    /* Doesn't start on new line */
    /* Cannot set width/height */
    /* Examples: span, a, strong */
}

/* INLINE-BLOCK */
.inline-block {
    display: inline-block;
    /* Inline flow but block-level properties */
    /* Can set width/height */
}

/* NONE */
.hidden {
    display: none;
    /* Completely removed from layout */
    /* Not accessible to screen readers */
}

/* CONTENTS */
.contents {
    display: contents;
    /* Element disappears, children become direct children of parent */
}

/* TABLE DISPLAY */
.table { display: table; }
.table-row { display: table-row; }
.table-cell { display: table-cell; }

/* VISIBILITY */
.invisible {
    visibility: hidden;
    /* Hidden but takes up space */
}

.visible {
    visibility: visible;
}

/* OPACITY */
.transparent {
    opacity: 0;
    /* Invisible but still takes space and clickable */
}

/* ACCESSIBILITY - visually hidden but screen reader accessible */
.sr-only {
    position: absolute;
    width: 1px;
    height: 1px;
    padding: 0;
    margin: -1px;
    overflow: hidden;
    clip: rect(0, 0, 0, 0);
    white-space: nowrap;
    border: 0;
}
Enter fullscreen mode Exit fullscreen mode

CSS Float & Clear (Legacy)

/* FLOAT (avoid in modern layouts - use Flexbox/Grid instead) */
.float-left {
    float: left;
    margin-right: 20px;
}

.float-right {
    float: right;
    margin-left: 20px;
}

/* CLEAR */
.clear-left { clear: left; }
.clear-right { clear: right; }
.clear-both { clear: both; }

/* CLEARFIX */
.clearfix::after {
    content: "";
    display: table;
    clear: both;
}
Enter fullscreen mode Exit fullscreen mode

4. CSS Flexbox Complete

What is Flexbox?

Definition: Flexbox (Flexible Box Layout) is a one-dimensional layout method for arranging items in rows or columns. It provides efficient ways to align, distribute, and order elements.
Flex Container Properties

.flex-container {
    /* ENABLE FLEXBOX */
    display: flex;
    /* or */
    display: inline-flex;

    /* FLEX DIRECTION */
    flex-direction: row;            /* → Left to right (default) */
    flex-direction: row-reverse;      /* ← Right to left */
    flex-direction: column;         /* ↓ Top to bottom */
    flex-direction: column-reverse;   /* ↑ Bottom to top */

    /* FLEX WRAP */
    flex-wrap: nowrap;      /* Single line (default) */
    flex-wrap: wrap;        /* Multiple lines, top to bottom */
    flex-wrap: wrap-reverse; /* Multiple lines, bottom to top */

    /* SHORTHAND */
    flex-flow: row wrap;

    /* JUSTIFY CONTENT (main axis alignment) */
    justify-content: flex-start;     /* Items packed to start */
    justify-content: flex-end;       /* Items packed to end */
    justify-content: center;         /* Items centered */
    justify-content: space-between;  /* Even spacing, edges at container edge */
    justify-content: space-around;   /* Even spacing including edges */
    justify-content: space-evenly;  /* Truly even spacing */

    /* ALIGN ITEMS (cross axis alignment) */
    align-items: stretch;      /* Fill container (default) */
    align-items: flex-start;   /* Align to cross-start */
    align-items: flex-end;     /* Align to cross-end */
    align-items: center;       /* Center on cross axis */
    align-items: baseline;     /* Align text baselines */

    /* ALIGN CONTENT (multi-line alignment) */
    align-content: flex-start;
    align-content: flex-end;
    align-content: center;
    align-content: space-between;
    align-content: space-around;
    align-content: stretch;

    /* GAP */
    gap: 20px;           /* Row and column gap */
    row-gap: 20px;       /* Gap between rows */
    column-gap: 10px;    /* Gap between columns */
}
Enter fullscreen mode Exit fullscreen mode

Flex Item Properties

.flex-item {
    /* FLEX GROW */
    flex-grow: 0;    /* Don't grow (default) */
    flex-grow: 1;    /* Grow to fill available space */
    flex-grow: 2;    /* Grow twice as much as flex-grow: 1 items */

    /* FLEX SHRINK */
    flex-shrink: 1;  /* Can shrink (default) */
    flex-shrink: 0;  /* Don't shrink */

    /* FLEX BASIS */
    flex-basis: auto;    /* Based on content size */
    flex-basis: 200px;   /* Start at 200px */
    flex-basis: 50%;     /* Start at 50% of container */
    flex-basis: content; /* Based on content */

    /* SHORTHAND: flex: grow shrink basis */
    flex: 1;              /* 1 1 0 */
    flex: 1 0 200px;      /* Grow, no shrink, 200px basis */
    flex: 0 1 auto;       /* No grow, can shrink, auto basis (default) */

    /* ALIGN SELF */
    align-self: auto;       /* Inherit from container */
    align-self: flex-start;
    align-self: flex-end;
    align-self: center;
    align-self: stretch;
    align-self: baseline;

    /* ORDER */
    order: 0;     /* Default */
    order: 1;     /* Move to end */
    order: -1;    /* Move to beginning */
}
Enter fullscreen mode Exit fullscreen mode

Flexbox Patterns

/* PATTERN 1: PERFECT CENTERING */
.center-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
}

/* PATTERN 2: NAVIGATION BAR */
.navbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem 2rem;
}

.nav-links {
    display: flex;
    gap: 2rem;
    list-style: none;
}

/* PATTERN 3: CARD LAYOUT */
.card-container {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
}

.card {
    flex: 1 1 300px;  /* Grow, shrink, 300px basis */
    /* Cards wrap automatically on small screens */
}

/* PATTERN 4: SIDEBAR LAYOUT */
.layout {
    display: flex;
    min-height: 100vh;
}

.sidebar {
    flex: 0 0 250px;  /* Fixed 250px, doesn't grow or shrink */
}

.main {
    flex: 1;  /* Takes remaining space */
}

/* PATTERN 5: EQUAL HEIGHT COLUMNS */
.columns {
    display: flex;
}

.column {
    flex: 1;  /* Equal width, automatic equal height */
}

/* PATTERN 6: STICKY FOOTER */
body {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
}

main {
    flex: 1;  /* Pushes footer down */
}

/* PATTERN 7: HOLY GRAIL LAYOUT */
.holy-grail {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
}

header, footer {
    flex: 0 0 auto;
}

.body {
    display: flex;
    flex: 1;
}

.nav, .aside {
    flex: 0 0 200px;
}

.content {
    flex: 1;
}

/* PATTERN 8: INPUT WITH BUTTON */
.input-group {
    display: flex;
}

.input-group input {
    flex: 1;
}

.input-group button {
    flex: 0 0 auto;
}

/* PATTERN 9: MEDIA OBJECT */
.media {
    display: flex;
    gap: 1rem;
}

.media-figure {
    flex: 0 0 auto;
}

.media-content {
    flex: 1;
}
Enter fullscreen mode Exit fullscreen mode

5. CSS Grid Complete

What is CSS Grid?

Definition: CSS Grid Layout is a two-dimensional layout system for handling both rows and columns simultaneously, making it ideal for complex page layouts.
Grid Container Properties

.grid-container {
    /* ENABLE GRID */
    display: grid;
    /* or */
    display: inline-grid;

    /* GRID TEMPLATE COLUMNS */
    grid-template-columns: 200px 200px 200px;  /* 3 fixed columns */
    grid-template-columns: 1fr 1fr 1fr;          /* 3 equal fractions */
    grid-template-columns: 2fr 1fr 1fr;          /* First is 2x others */
    grid-template-columns: 200px 1fr 200px;      /* Fixed sides, flexible middle */
    grid-template-columns: repeat(3, 1fr);       /* Repeat 1fr three times */
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); /* Responsive */
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));

    /* GRID TEMPLATE ROWS */
    grid-template-rows: 100px 200px;
    grid-template-rows: auto 1fr auto;  /* Header, content, footer */

    /* GRID TEMPLATE AREAS */
    grid-template-areas:
        "header header header"
        "sidebar content content"
        "footer footer footer";

    /* GAP */
    gap: 20px;
    row-gap: 20px;
    column-gap: 10px;

    /* JUSTIFY ITEMS (horizontal alignment in cells) */
    justify-items: start;    /* Left */
    justify-items: end;      /* Right */
    justify-items: center;   /* Center */
    justify-items: stretch;  /* Fill (default) */

    /* ALIGN ITEMS (vertical alignment in cells) */
    align-items: start;      /* Top */
    align-items: end;        /* Bottom */
    align-items: center;     /* Center */
    align-items: stretch;    /* Fill (default) */

    /* PLACE ITEMS (shorthand) */
    place-items: center center;  /* align justify */

    /* JUSTIFY CONTENT (grid alignment in container) */
    justify-content: start;
    justify-content: end;
    justify-content: center;
    justify-content: space-between;
    justify-content: space-around;
    justify-content: space-evenly;

    /* ALIGN CONTENT */
    align-content: start;
    align-content: center;
    align-content: space-between;

    /* GRID AUTO FLOW */
    grid-auto-flow: row;       /* Fill rows first (default) */
    grid-auto-flow: column;    /* Fill columns first */
    grid-auto-flow: dense;     /* Fill holes with smaller items */

    /* IMPLICIT GRID SIZING */
    grid-auto-rows: 100px;
    grid-auto-columns: 200px;
}
Enter fullscreen mode Exit fullscreen mode

Grid Item Properties

.grid-item {
    /* GRID COLUMN PLACEMENT */
    grid-column: 1;           /* Start at column 1 */
    grid-column: 1 / 3;       /* Start at 1, end before 3 (spans 2) */
    grid-column: span 2;     /* Span 2 columns */
    grid-column: 1 / -1;      /* Span all columns */

    /* GRID ROW PLACEMENT */
    grid-row: 1;
    grid-row: 1 / 3;
    grid-row: span 2;

    /* GRID AREA (shorthand) */
    grid-area: header;        /* Named area */
    grid-area: 1 / 1 / 3 / 3; /* row-start / col-start / row-end / col-end */

    /* ALIGN SELF */
    justify-self: start;
    align-self: center;
    place-self: center;  /* align justify */

    /* ORDER */
    order: 1;
}
Enter fullscreen mode Exit fullscreen mode

Grid Layout Patterns

/* PATTERN 1: BASIC GRID */
.basic-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
}

/* PATTERN 2: RESPONSIVE GRID */
.responsive-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
}

/* PATTERN 3: HOLY GRAIL LAYOUT */
.holy-grail {
    display: grid;
    grid-template-areas:
        "header header header"
        "nav content sidebar"
        "footer footer footer";
    grid-template-columns: 200px 1fr 200px;
    grid-template-rows: auto 1fr auto;
    min-height: 100vh;
    gap: 10px;
}

.holy-grail > header { grid-area: header; }
.holy-grail > nav { grid-area: nav; }
.holy-grail > main { grid-area: content; }
.holy-grail > aside { grid-area: sidebar; }
.holy-grail > footer { grid-area: footer; }

/* PATTERN 4: DASHBOARD LAYOUT */
.dashboard {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-template-rows: repeat(3, 200px);
    gap: 20px;
}

.dashboard .widget-large {
    grid-column: span 2;
    grid-row: span 2;
}

.dashboard .widget-wide {
    grid-column: span 2;
}

.dashboard .widget-tall {
    grid-row: span 2;
}

/* PATTERN 5: MASONRY-STYLE LAYOUT */
.masonry {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    grid-auto-rows: 20px;
    gap: 10px;
}

.masonry-item {
    grid-row: span 5;  /* Approximate height */
}

/* PATTERN 6: CENTERED CONTENT */
.grid-center {
    display: grid;
    place-items: center;
    min-height: 100vh;
}

/* PATTERN 7: ASYMMETRIC LAYOUT */
.asymmetric {
    display: grid;
    grid-template-columns: 2fr 1fr 1fr;
    gap: 20px;
}

/* PATTERN 8: FORM LAYOUT */
.form-grid {
    display: grid;
    grid-template-columns: 150px 1fr;
    gap: 1rem;
    align-items: center;
}

.form-grid label {
    text-align: right;
}

.form-grid .full-width {
    grid-column: 1 / -1;
}

/* PATTERN 9: GALLERY WITH OVERLAY */
.gallery {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10px;
}

.gallery-item {
    position: relative;
    aspect-ratio: 1;
}

.gallery-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.gallery-item .overlay {
    position: absolute;
    inset: 0;
    background: rgba(0,0,0,0.5);
    opacity: 0;
    transition: opacity 0.3s;
}

.gallery-item:hover .overlay {
    opacity: 1;
}
Enter fullscreen mode Exit fullscreen mode

6. Responsive Design Complete

Media Queries

/* MOBILE FIRST APPROACH (Recommended) */

/* Base styles - Mobile */
body {
    font-size: 14px;
    padding: 10px;
}

.container {
    width: 100%;
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 15px;
}

/* Small devices (landscape phones, 576px and up) */
@media (min-width: 576px) {
    body {
        font-size: 15px;
    }

    .container {
        max-width: 540px;
    }
}

/* Medium devices (tablets, 768px and up) */
@media (min-width: 768px) {
    body {
        font-size: 16px;
    }

    .container {
        max-width: 720px;
    }

    .grid {
        grid-template-columns: repeat(2, 1fr);
    }
}

/* Large devices (desktops, 992px and up) */
@media (min-width: 992px) {
    .container {
        max-width: 960px;
    }

    .grid {
        grid-template-columns: repeat(3, 1fr);
    }
}

/* Extra large devices (large desktops, 1200px and up) */
@media (min-width: 1200px) {
    .container {
        max-width: 1140px;
    }
}

/* Extra extra large (1400px and up) */
@media (min-width: 1400px) {
    .container {
        max-width: 1320px;
    }
}

/* RANGE QUERIES */
@media (min-width: 768px) and (max-width: 991px) {
    /* Only tablets */
}

/* ORIENTATION */
@media (orientation: landscape) {
    /* Landscape mode */
}

@media (orientation: portrait) {
    /* Portrait mode */
}

/* ASPECT RATIO */
@media (min-aspect-ratio: 16/9) {
    /* Widescreen */
}

/* DARK MODE */
@media (prefers-color-scheme: dark) {
    body {
        background-color: #1a1a1a;
        color: #ffffff;
    }
}

/* REDUCED MOTION (Accessibility) */
@media (prefers-reduced-motion: reduce) {
    * {
        animation-duration: 0.01ms !important;
        animation-iteration-count: 1 !important;
        transition-duration: 0.01ms !important;
    }
}

/* HIGH CONTRAST MODE */
@media (prefers-contrast: high) {
    /* High contrast styles */
}

/* PRINT STYLES */
@media print {
    .no-print {
        display: none !important;
    }

    body {
        font-size: 12pt;
        color: black;
        background: white;
    }

    a[href]::after {
        content: " (" attr(href) ")";
    }
}

/* CONTAINER QUERIES (Modern) */
.card-container {
    container-type: inline-size;
    container-name: cards;
}

@container cards (min-width: 400px) {
    .card {
        display: flex;
        gap: 1rem;
    }
}

@container cards (min-width: 600px) {
    .card {
        display: grid;
        grid-template-columns: 200px 1fr;
    }
}
Enter fullscreen mode Exit fullscreen mode

Responsive Typography

/* METHOD 1: FLUID TYPOGRAPHY with clamp() */
:root {
    --fs-sm: clamp(0.875rem, 0.8rem + 0.25vw, 1rem);
    --fs-base: clamp(1rem, 0.9rem + 0.5vw, 1.125rem);
    --fs-md: clamp(1.125rem, 1rem + 0.75vw, 1.25rem);
    --fs-lg: clamp(1.25rem, 1rem + 1vw, 1.5rem);
    --fs-xl: clamp(1.5rem, 1.25rem + 1.5vw, 2rem);
    --fs-2xl: clamp(2rem, 1.5rem + 2vw, 3rem);
}

body {
    font-size: var(--fs-base);
}

h1 { font-size: var(--fs-2xl); }
h2 { font-size: var(--fs-xl); }
h3 { font-size: var(--fs-lg); }

/* METHOD 2: VIEWPORT UNITS */
.fluid-text {
    font-size: calc(14px + 0.5vw);
}

/* METHOD 3: STEP SCALE */
:root {
    --step--2: clamp(0.64rem, 0.79rem + -0.18vw, 0.79rem);
    --step--1: clamp(0.8rem, 0.89rem + -0.11vw, 0.89rem);
    --step-0: clamp(1rem, 1rem + 0vw, 1rem);
    --step-1: clamp(1.25rem, 1.12rem + 0.16vw, 1.41rem);
    --step-2: clamp(1.56rem, 1.26rem + 0.38vw, 2rem);
    --step-3: clamp(1.95rem, 1.41rem + 0.7vw, 2.83rem);
    --step-4: clamp(2.44rem, 1.57rem + 1.15vw, 4rem);
    --step-5: clamp(3.05rem, 1.75rem + 1.79vw, 5.65rem);
}
Enter fullscreen mode Exit fullscreen mode

Responsive Images

/* FLUID IMAGES */
img {
    max-width: 100%;
    height: auto;
    display: block;
}

/* OBJECT FIT */
.cover-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.contain-image {
    width: 100%;
    height: 100%;
    object-fit: contain;
}

/* ASPECT RATIO */
.video-container {
    aspect-ratio: 16 / 9;
    width: 100%;
}

.square {
    aspect-ratio: 1 / 1;
}

/* ART DIRECTION */
.responsive-hero {
    background-image: url('mobile.jpg');
    background-size: cover;
    height: 300px;
}

@media (min-width: 768px) {
    .responsive-hero {
        background-image: url('tablet.jpg');
        height: 400px;
    }
}

@media (min-width: 1200px) {
    .responsive-hero {
        background-image: url('desktop.jpg');
        height: 600px;
    }
}
Enter fullscreen mode Exit fullscreen mode

7. CSS Animations & Effects

CSS Transitions

/* BASIC TRANSITION */
.button {
    background-color: blue;
    color: white;
    padding: 10px 20px;
    transition: background-color 0.3s ease;
}

.button:hover {
    background-color: darkblue;
}

/* TRANSITION PROPERTIES */
.element {
    /* What to animate */
    transition-property: all;
    transition-property: background-color, transform, opacity;

    /* Duration */
    transition-duration: 0.3s;
    transition-duration: 300ms;

    /* Timing function */
    transition-timing-function: ease;         /* Slow start, fast middle, slow end */
    transition-timing-function: linear;       /* Constant speed */
    transition-timing-function: ease-in;      /* Slow start */
    transition-timing-function: ease-out;     /* Slow end */
    transition-timing-function: ease-in-out;  /* Slow start and end */
    transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); /* Custom */

    /* Delay */
    transition-delay: 0.5s;

    /* SHORTHAND */
    transition: all 0.3s ease 0s;
    transition: background-color 0.3s ease, transform 0.5s ease-in-out;
}

/* COMMON TRANSITION PATTERNS */

/* Button hover lift */
.btn-hover {
    transition: transform 0.2s, box-shadow 0.2s;
}

.btn-hover:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}

/* Smooth color change */
.link-hover {
    transition: color 0.2s;
}

.link-hover:hover {
    color: #ff6b6b;
}

/* Expand on hover */
.expand-hover {
    transition: width 0.3s ease;
    width: 200px;
}

.expand-hover:hover {
    width: 250px;
}

/* Fade in */
.fade-in {
    opacity: 0;
    transition: opacity 0.5s ease;
}

.fade-in.visible {
    opacity: 1;
}

/* Slide in */
.slide-in {
    transform: translateX(-100%);
    transition: transform 0.3s ease;
}

.slide-in.visible {
    transform: translateX(0);
}
Enter fullscreen mode Exit fullscreen mode

CSS Transforms

/* 2D TRANSFORMS */
.element {
    /* TRANSLATE */
    transform: translate(50px, 100px);  /* X, Y */
    transform: translateX(50px);
    transform: translateY(100px);

    /* SCALE */
    transform: scale(1.5);        /* Uniform */
    transform: scale(1.5, 2);     /* X, Y */
    transform: scaleX(1.5);
    transform: scaleY(2);

    /* ROTATE */
    transform: rotate(45deg);
    transform: rotate(-90deg);

    /* SKEW */
    transform: skew(10deg, 20deg);
    transform: skewX(10deg);
    transform: skewY(20deg);

    /* MATRIX (combine all) */
    transform: matrix(1, 0, 0, 1, 50, 100);

    /* ORIGIN */
    transform-origin: center center;  /* Default */
    transform-origin: top left;
    transform-origin: bottom right;
    transform-origin: 25% 75%;
}

/* 3D TRANSFORMS */
.element-3d {
    perspective: 1000px;
    transform-style: preserve-3d;

    transform: translateZ(50px);
    transform: rotateX(45deg);
    transform: rotateY(45deg);
    transform: rotateZ(45deg);
    transform: scaleZ(1.5);
}

/* COMMON TRANSFORM PATTERNS */

/* Center with transform */
.center-transform {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

/* Card flip */
.flip-card {
    perspective: 1000px;
}

.flip-card-inner {
    transition: transform 0.6s;
    transform-style: preserve-3d;
}

.flip-card:hover .flip-card-inner {
    transform: rotateY(180deg);
}

.flip-card-front, .flip-card-back {
    backface-visibility: hidden;
}

.flip-card-back {
    transform: rotateY(180deg);
}

/* Hover zoom */
.zoom-hover {
    overflow: hidden;
}

.zoom-hover img {
    transition: transform 0.3s;
}

.zoom-hover:hover img {
    transform: scale(1.1);
}

/* 3D Button */
.btn-3d {
    transform: perspective(500px) rotateX(10deg);
    transition: transform 0.2s;
}

.btn-3d:hover {
    transform: perspective(500px) rotateX(0deg) translateY(-5px);
}
Enter fullscreen mode Exit fullscreen mode

CSS Animations

/* DEFINE KEYFRAMES */
@keyframes slideIn {
    from {
        transform: translateX(-100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

@keyframes fadeIn {
    0% { opacity: 0; }
    100% { opacity: 1; }
}

@keyframes bounce {
    0%, 20%, 50%, 80%, 100% {
        transform: translateY(0);
    }
    40% {
        transform: translateY(-30px);
    }
    60% {
        transform: translateY(-15px);
    }
}

@keyframes pulse {
    0% {
        transform: scale(1);
        opacity: 1;
    }
    50% {
        transform: scale(1.1);
        opacity: 0.8;
    }
    100% {
        transform: scale(1);
        opacity: 1;
    }
}

@keyframes shake {
    0%, 100% { transform: translateX(0); }
    10%, 30%, 50%, 70%, 90% { transform: translateX(-10px); }
    20%, 40%, 60%, 80% { transform: translateX(10px); }
}

@keyframes rotate {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}

@keyframes gradient {
    0% { background-position: 0% 50%; }
    50% { background-position: 100% 50%; }
    100% { background-position: 0% 50%; }
}

@keyframes float {
    0%, 100% { transform: translateY(0); }
    50% { transform: translateY(-20px); }
}

@keyframes glow {
    0%, 100% { box-shadow: 0 0 5px #fff; }
    50% { box-shadow: 0 0 20px #fff, 0 0 30px #ff00de; }
}

/* APPLY ANIMATIONS */
.element {
    animation-name: slideIn;
    animation-duration: 1s;
    animation-timing-function: ease;
    animation-delay: 0s;
    animation-iteration-count: 1;
    animation-direction: normal;
    animation-fill-mode: forwards;
    animation-play-state: running;

    /* SHORTHAND */
    animation: slideIn 1s ease 0s 1 normal forwards;
}

/* COMMON ANIMATION CLASSES */
.animate-fade-in {
    animation: fadeIn 0.5s ease;
}

.animate-bounce {
    animation: bounce 2s infinite;
}

.animate-pulse {
    animation: pulse 1s infinite;
}

.animate-shake {
    animation: shake 0.5s;
}

.animate-spin {
    animation: rotate 1s linear infinite;
}

.animate-float {
    animation: float 3s ease-in-out infinite;
}

.animate-glow {
    animation: glow 2s infinite;
}

/* LOADING SPINNER */
.spinner {
    width: 50px;
    height: 50px;
    border: 5px solid #f3f3f3;
    border-top: 5px solid #3498db;
    border-radius: 50%;
    animation: rotate 1s linear infinite;
}

/* TYPING EFFECT */
@keyframes typing {
    from { width: 0; }
    to { width: 100%; }
}

@keyframes blink {
    50% { border-color: transparent; }
}

.typewriter {
    overflow: hidden;
    border-right: 2px solid;
    white-space: nowrap;
    animation: 
        typing 3.5s steps(40, end),
        blink 0.75s step-end infinite;
}

/* ANIMATED GRADIENT BACKGROUND */
.animated-gradient {
    background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
    background-size: 400% 400%;
    animation: gradient 15s ease infinite;
}
Enter fullscreen mode Exit fullscreen mode

CSS Filters & Effects

/* CSS FILTERS */
.image-filter {
    filter: blur(5px);
    filter: brightness(0.5);    /* 0-1 or % */
    filter: contrast(200%);
    filter: grayscale(100%);
    filter: hue-rotate(90deg);
    filter: invert(100%);
    filter: opacity(50%);
    filter: saturate(200%);
    filter: sepia(100%);
    filter: drop-shadow(5px 5px 10px rgba(0,0,0,0.5));

    /* MULTIPLE FILTERS */
    filter: brightness(110%) contrast(120%) saturate(130%);
}

/* BLEND MODES */
.blend-multiply {
    mix-blend-mode: multiply;
}

.blend-screen {
    mix-blend-mode: screen;
}

.blend-overlay {
    mix-blend-mode: overlay;
}

/* BACKDROP FILTER (glass effect) */
.glass {
    background: rgba(255, 255, 255, 0.2);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.3);
}

/* CLIP PATH */
.clip-circle {
    clip-path: circle(50%);
}

.clip-triangle {
    clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
}

.clip-hexagon {
    clip-path: polygon(25% 0%, 75% 0%, 100% 50%, 75% 100%, 25% 100%, 0% 50%);
}

/* MASK */
.mask-gradient {
    mask-image: linear-gradient(to bottom, black 50%, transparent 100%);
    -webkit-mask-image: linear-gradient(to bottom, black 50%, transparent 100%);
}

/* SHAPE OUTSIDE */
.shape-float {
    float: left;
    shape-outside: circle(50%);
    width: 200px;
    height: 200px;
    border-radius: 50%;
}
Enter fullscreen mode Exit fullscreen mode

8. JavaScript Fundamentals

What is JavaScript?

Definition: JavaScript is a high-level, interpreted programming language that enables interactive web pages. It is a multi-paradigm language supporting event-driven, functional, and imperative programming styles.
Variables & Data Types

// VARIABLE DECLARATIONS

// let - Block-scoped, can reassign
let count = 0;
count = 1;  // Valid
// let count = 2;  // Error: Already declared

// const - Block-scoped, cannot reassign
const PI = 3.14159;
// PI = 3.14;  // Error: Assignment to constant

// But const objects/arrays can be modified
const user = { name: 'John' };
user.name = 'Jane';  // Valid
user.age = 30;       // Valid
// user = {};        // Error: Cannot reassign

const arr = [1, 2, 3];
arr.push(4);  // Valid
// arr = [];  // Error

// var - Function-scoped (avoid in modern code)
var oldWay = 'deprecated';

// NAMING CONVENTIONS
// camelCase for variables and functions
let userName = 'John';
function getUserData() {}

// PascalCase for classes
class UserProfile {}

// UPPER_SNAKE_CASE for constants
const MAX_USERS = 100;
const API_BASE_URL = 'https://api.example.com';

// DATA TYPES

// PRIMITIVE TYPES
const str = 'Hello World';           // String
const num = 42;                       // Number
const float = 3.14;                   // Number (no separate float)
const bool = true;                    // Boolean
const nothing = null;                 // Null (intentional absence)
const notDefined = undefined;         // Undefined (not assigned)
const sym = Symbol('id');             // Symbol (unique identifier)
const big = 9007199254740991n;        // BigInt (large integers)

// REFERENCE TYPES
const obj = { name: 'John', age: 30 };  // Object
const array = [1, 2, 3, 4, 5];          // Array
const fn = function() {};               // Function
const date = new Date();                // Date
const regex = /pattern/;                // RegExp

// TYPE CHECKING
console.log(typeof 'Hello');     // "string"
console.log(typeof 42);          // "number"
console.log(typeof true);        // "boolean"
console.log(typeof undefined);   // "undefined"
console.log(typeof null);        // "object" (JavaScript quirk!)
console.log(typeof {});          // "object"
console.log(typeof []);          // "object" (use Array.isArray())
console.log(typeof function(){}); // "function"

// Check if array
console.log(Array.isArray([]));  // true

// Check if null
console.log(value === null);     // true

// TRUTHY & FALSY VALUES

// FALSY (evaluate to false in boolean context)
false, 0, -0, 0n, '', null, undefined, NaN

// TRUTHY (everything else)
true, 1, 'hello', [], {}, function(){}, '0', 'false'
Enter fullscreen mode Exit fullscreen mode

Operators

// ARITHMETIC OPERATORS
let a = 10;
let b = 3;

console.log(a + b);   // 13 (Addition)
console.log(a - b);   // 7 (Subtraction)
console.log(a * b);   // 30 (Multiplication)
console.log(a / b);   // 3.333... (Division)
console.log(a % b);   // 1 (Modulus/Remainder)
console.log(a ** b);  // 1000 (Exponentiation)

// INCREMENT/DECREMENT
let x = 5;
console.log(x++);     // 5 (Post-increment: returns then increments)
console.log(++x);     // 7 (Pre-increment: increments then returns)
console.log(x--);     // 7 (Post-decrement)
console.log(--x);     // 5 (Pre-decrement)

// ASSIGNMENT OPERATORS
let y = 10;
y += 5;   // y = y + 5  → 15
y -= 3;   // y = y - 3  → 12
y *= 2;   // y = y * 2  → 24
y /= 4;   // y = y / 4  → 6
y %= 5;   // y = y % 5  → 1
y **= 2;  // y = y ** 2 → 1

// COMPARISON OPERATORS
console.log(5 == '5');    // true (Loose equality, type coercion)
console.log(5 === '5');   // false (Strict equality, no coercion)
console.log(5 != '5');    // false (Loose inequality)
console.log(5 !== '5');   // true (Strict inequality)

console.log(5 > 3);       // true
console.log(5 < 3);       // false
console.log(5 >= 5);      // true
console.log(5 <= 4);      // false

// LOGICAL OPERATORS
const isAdult = true;
const hasLicense = false;

console.log(isAdult && hasLicense);  // false (AND)
console.log(isAdult || hasLicense);  // true (OR)
console.log(!isAdult);               // false (NOT)

// SHORT-CIRCUIT EVALUATION
const result = null || 'default';    // 'default'
const result2 = 'value' || 'default'; // 'value'
const result3 = null && 'value';     // null
const result4 = 'value' && 'next';   // 'next'

// NULLISH COALESCING (??)
const value1 = null ?? 'default';     // 'default'
const value2 = undefined ?? 'default'; // 'default'
const value3 = 0 ?? 'default';        // 0 (not null/undefined)
const value4 = '' ?? 'default';       // '' (not null/undefined)

// OPTIONAL CHAINING (?.)
const user = {
    name: 'John',
    address: {
        city: 'New York'
    }
};

console.log(user?.address?.city);     // 'New York'
console.log(user?.contact?.phone);    // undefined (no error)

// TERNARY OPERATOR
const age = 20;
const status = age >= 18 ? 'Adult' : 'Minor';

// MULTIPLE CONDITIONS
const category = age < 13 ? 'Child' :
                 age < 20 ? 'Teenager' :
                 age < 65 ? 'Adult' : 'Senior';
Enter fullscreen mode Exit fullscreen mode

Control Flow

// IF...ELSE STATEMENTS
const score = 85;

if (score >= 90) {
    console.log('Grade: A');
} else if (score >= 80) {
    console.log('Grade: B');
} else if (score >= 70) {
    console.log('Grade: C');
} else if (score >= 60) {
    console.log('Grade: D');
} else {
    console.log('Grade: F');
}

// SWITCH STATEMENT
const day = 'Monday';

switch (day) {
    case 'Monday':
        console.log('Start of work week');
        break;
    case 'Tuesday':
    case 'Wednesday':
    case 'Thursday':
        console.log('Midweek');
        break;
    case 'Friday':
        console.log('Almost weekend!');
        break;
    case 'Saturday':
    case 'Sunday':
        console.log('Weekend!');
        break;
    default:
        console.log('Invalid day');
}

// FOR LOOP
for (let i = 0; i < 5; i++) {
    console.log(i);  // 0, 1, 2, 3, 4
}

// Loop through array
const fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

// WHILE LOOP
let count = 0;
while (count < 5) {
    console.log(count);
    count++;
}

// DO...WHILE LOOP (executes at least once)
let num = 0;
do {
    console.log(num);
    num++;
} while (num < 5);

// FOR...OF (iterate over iterable values)
for (const fruit of fruits) {
    console.log(fruit);
}

// FOR...IN (iterate over object keys)
const person = { name: 'John', age: 30, city: 'NYC' };
for (const key in person) {
    console.log(`${key}: ${person[key]}`);
}

// BREAK & CONTINUE
for (let i = 0; i < 10; i++) {
    if (i === 5) break;      // Exit loop completely
    if (i % 2 === 0) continue; // Skip to next iteration
    console.log(i);          // 1, 3
}

// LABELED STATEMENTS
outerLoop:
for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
        if (i === 1 && j === 1) {
            break outerLoop;  // Break outer loop
        }
        console.log(i, j);
    }
}
Enter fullscreen mode Exit fullscreen mode

Functions

// FUNCTION DECLARATION
function greet(name) {
    return `Hello, ${name}!`;
}

console.log(greet('John'));  // "Hello, John!"

// FUNCTION EXPRESSION
const add = function(a, b) {
    return a + b;
};

// ARROW FUNCTION (ES6+)
const multiply = (a, b) => a * b;
const square = x => x * x;
const greetArrow = name => `Hello, ${name}!`;

// MULTI-LINE ARROW FUNCTION
const calculate = (a, b) => {
    const sum = a + b;
    const product = a * b;
    return { sum, product };
};

// DEFAULT PARAMETERS
function greetUser(name = 'Guest', greeting = 'Hello') {
    return `${greeting}, ${name}!`;
}

console.log(greetUser());              // "Hello, Guest!"
console.log(greetUser('John'));        // "Hello, John!"
console.log(greetUser('John', 'Hi'));  // "Hi, John!"

// REST PARAMETERS (...)
function sum(...numbers) {
    return numbers.reduce((total, num) => total + num, 0);
}

console.log(sum(1, 2, 3, 4, 5));  // 15

// SPREAD OPERATOR
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];  // [1, 2, 3, 4, 5, 6]

// DESTRUCTURING PARAMETERS
function displayUser({ name, age, email = 'N/A' }) {
    console.log(`Name: ${name}, Age: ${age}, Email: ${email}`);
}

const user = { name: 'John', age: 30 };
displayUser(user);

// IIFE (Immediately Invoked Function Expression)
(function() {
    console.log('This runs immediately');
})();

// ARROW IIFE
(() => {
    console.log('Arrow IIFE');
})();

// CALLBACK FUNCTIONS
function processData(data, callback) {
    const processed = data.toUpperCase();
    callback(processed);
}

processData('hello', (result) => {
    console.log(result);  // "HELLO"
});

// HIGHER-ORDER FUNCTIONS
function createMultiplier(factor) {
    return function(number) {
        return number * factor;
    };
}

const double = createMultiplier(2);
const triple = createMultiplier(3);

console.log(double(5));  // 10
console.log(triple(5));  // 15

// RECURSION
function factorial(n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}

console.log(factorial(5));  // 120

// CLOSURES
function makeCounter() {
    let count = 0;

    return {
        increment() {
            return ++count;
        },
        decrement() {
            return --count;
        },
        getCount() {
            return count;
        }
    };
}

const counter = makeCounter();
console.log(counter.increment());  // 1
console.log(counter.increment());  // 2
console.log(counter.getCount());   // 2
Enter fullscreen mode Exit fullscreen mode

Arrays

// ARRAY CREATION
const arr1 = [1, 2, 3, 4, 5];
const arr2 = new Array(5);        // [empty × 5]
const arr3 = Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']
const arr4 = Array.of(1, 2, 3);   // [1, 2, 3]

// ACCESSING ELEMENTS
console.log(arr1[0]);      // 1
console.log(arr1.at(-1));  // 5 (last element, ES2022)

// ARRAY PROPERTIES
console.log(arr1.length);  // 5

// ADDING/REMOVING ELEMENTS
const arr = [1, 2, 3];

arr.push(4);           // Add to end → [1, 2, 3, 4]
arr.pop();             // Remove from end → [1, 2, 3]
arr.unshift(0);        // Add to start → [0, 1, 2, 3]
arr.shift();           // Remove from start → [1, 2, 3]

arr.splice(1, 1);      // Remove 1 element at index 1 → [1, 3]
arr.splice(1, 0, 2);   // Insert at index 1 → [1, 2, 3]
arr.splice(1, 1, 4, 5); // Replace → [1, 4, 5, 3]

// SEARCHING
arr.indexOf(3);        // 2 (first occurrence)
arr.lastIndexOf(3);    // last occurrence
arr.includes(3);       // true
arr.find(x => x > 2);  // 3 (first match)
arr.findIndex(x => x > 2); // 2 (index of first match)
arr.findLast(x => x < 4);  // 3 (last match, ES2023)
arr.findLastIndex(x => x < 4); // index of last match

// ITERATION METHODS
arr.forEach((item, index) => {
    console.log(`${index}: ${item}`);
});

// TRANSFORMATION METHODS
const doubled = arr.map(x => x * 2);
const evens = arr.filter(x => x % 2 === 0);
const sum = arr.reduce((acc, x) => acc + x, 0);
const product = arr.reduce((acc, x) => acc * x, 1);

// SOME & EVERY
const hasEven = arr.some(x => x % 2 === 0);
const allPositive = arr.every(x => x > 0);

// SORTING
const nums = [3, 1, 4, 1, 5];
nums.sort((a, b) => a - b);   // Ascending [1, 1, 3, 4, 5]
nums.sort((a, b) => b - a);   // Descending [5, 4, 3, 1, 1]

const words = ['banana', 'Apple', 'cherry'];
words.sort((a, b) => a.localeCompare(b));  // Case-sensitive sort

// IMMUTABLE SORT (ES2023)
const sorted = nums.toSorted((a, b) => a - b);

// OTHER METHODS
const sliced = arr.slice(1, 3);    // Extract portion [start, end)
const joined = arr.join(', ');     // "1, 2, 3"
const reversed = arr.reverse();    // Mutates original
const immutableReversed = arr.toReversed(); // ES2023, doesn't mutate

// FLAT ARRAYS
const nested = [1, [2, 3], [4, [5, 6]]];
console.log(nested.flat());      // [1, 2, 3, 4, [5, 6]]
console.log(nested.flat(2));     // [1, 2, 3, 4, 5, 6]

// FLATMAP
const sentences = ['Hello world', 'Goodbye moon'];
const words = sentences.flatMap(s => s.split(' '));
// ['Hello', 'world', 'Goodbye', 'moon']

// WITH METHOD (ES2023) - immutable update
const newArr = arr.with(1, 99);  // Replace index 1 with 99

// GROUPING (ES2024)
const inventory = [
    { name: 'apples', type: 'fruit', quantity: 10 },
    { name: 'bananas', type: 'fruit', quantity: 5 },
    { name: 'carrots', type: 'vegetable', quantity: 8 }
];

const grouped = Object.groupBy(inventory, item => item.type);
// { fruit: [...], vegetable: [...] }
Enter fullscreen mode Exit fullscreen mode

Objects

// OBJECT CREATION
const person = {
    firstName: 'John',
    lastName: 'Doe',
    age: 30,
    email: 'john@example.com',

    // Method
    getFullName() {
        return `${this.firstName} ${this.lastName}`;
    },

    // Getter
    get info() {
        return `${this.getFullName()}, ${this.age} years old`;
    },

    // Setter
    set setAge(value) {
        if (value > 0) this.age = value;
    }
};

// ACCESSING PROPERTIES
console.log(person.firstName);      // Dot notation
console.log(person['lastName']);    // Bracket notation
const key = 'age';
console.log(person[key]);           // Dynamic key

// ADDING/MODIFYING/DELETING
person.city = 'New York';           // Add
person.age = 31;                    // Modify
delete person.email;                // Delete

// CHECKING PROPERTIES
console.log('age' in person);                    // true
console.log(person.hasOwnProperty('age'));       // true
console.log(Object.prototype.hasOwnProperty.call(person, 'age')); // Safer

// OBJECT METHODS
const keys = Object.keys(person);      // ['firstName', 'lastName', ...]
const values = Object.values(person);  // ['John', 'Doe', ...]
const entries = Object.entries(person); // [['firstName', 'John'], ...]

// OBJECT FROM ENTRIES
const obj = Object.fromEntries([['a', 1], ['b', 2]]); // { a: 1, b: 2 }

// ASSIGN (shallow merge)
const target = { a: 1 };
const source = { b: 2, c: 3 };
const merged = Object.assign(target, source); // { a: 1, b: 2, c: 3 }

// SPREAD SYNTAX (preferred)
const merged2 = { ...target, ...source };

// FREEZE & SEAL
const frozen = Object.freeze({ a: 1 });
// frozen.a = 2;  // Error in strict mode

const sealed = Object.seal({ a: 1 });
sealed.a = 2;  // OK
// sealed.b = 3;  // Error

// DESTRUCTURING
const { firstName, lastName, age = 25 } = person;
const { firstName: fName, lastName: lName } = person;  // Rename

// NESTED DESTRUCTURING
const user = {
    name: 'John',
    address: {
        city: 'NYC',
        zip: '10001'
    }
};

const { name, address: { city, zip } } = user;

// REST IN DESTRUCTURING
const { firstName, ...rest } = person;
// rest contains all other properties

// OBJECT SHORTHAND
const name = 'John';
const age = 30;
const user = { name, age };  // { name: 'John', age: 30 }

// COMPUTED PROPERTY NAMES
const propName = 'dynamic';
const obj = {
    [propName]: 'value',
    [`computed${propName}`]: 'another value'
};

// OPTIONAL CHAINING
console.log(user?.address?.city);  // undefined if any part is null/undefined

// NULLISH COALESCING
const value = user.settings?.theme ?? 'default';
Enter fullscreen mode Exit fullscreen mode

Asynchronous JavaScript

// CALLBACKS (Old way)
function fetchData(callback) {
    setTimeout(() => {
        const data = { id: 1, name: 'John' };
        callback(data);
    }, 1000);
}

fetchData((data) => {
    console.log(data);
});

// PROMISES
const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        const success = true;
        if (success) {
            resolve('Data loaded');
        } else {
            reject('Error loading data');
        }
    }, 1000);
});

promise
    .then(result => {
        console.log(result);
        return result + '!';
    })
    .then(modified => {
        console.log(modified);
    })
    .catch(error => {
        console.error(error);
    })
    .finally(() => {
        console.log('Always runs');
    });

// PROMISE METHODS
const p1 = fetch('/api/users');
const p2 = fetch('/api/posts');
const p3 = fetch('/api/comments');

Promise.all([p1, p2, p3])           // All must succeed
    .then(responses => Promise.all(responses.map(r => r.json())))
    .then(data => console.log(data));

Promise.allSettled([p1, p2, p3])    // Wait for all, regardless of success
    .then(results => console.log(results));

Promise.race([p1, p2, p3])          // First to complete
    .then(response => console.log(response));

Promise.any([p1, p2, p3])           // First to succeed
    .then(response => console.log(response));

// ASYNC/AWAIT (Modern)
async function loadData() {
    try {
        const response = await fetch('/api/data');

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error:', error);
        throw error;
    } finally {
        console.log('Request completed');
    }
}

// Using async function
(async () => {
    try {
        const data = await loadData();
        console.log(data);
    } catch (error) {
        console.error('Failed to load:', error);
    }
})();

// PARALLEL EXECUTION
async function loadMultiple() {
    const [users, posts, comments] = await Promise.all([
        fetch('/api/users').then(r => r.json()),
        fetch('/api/posts').then(r => r.json()),
        fetch('/api/comments').then(r => r.json())
    ]);

    return { users, posts, comments };
}

// TOP-LEVEL AWAIT (ES2022+ in modules)
// const data = await fetch('/api/data').then(r => r.json());

// ERROR HANDLING PATTERNS
async function safeFetch(url) {
    try {
        const response = await fetch(url);
        if (!response.ok) throw new Error(response.statusText);
        return await response.json();
    } catch (error) {
        console.error(`Failed to fetch ${url}:`, error);
        return null;  // Return default value
    }
}
Enter fullscreen mode Exit fullscreen mode

9. Modern JavaScript (ES6+)

Template Literals

const name = 'John';
const age = 30;

// Basic interpolation
const greeting = `Hello, ${name}!`;

// Multi-line strings
const html = `
    <div>
        <h1>${name}</h1>
        <p>Age: ${age}</p>
    </div>
`;

// Expression evaluation
const result = `Sum: ${2 + 2}`;

// Tagged templates
function highlight(strings, ...values) {
    return strings.reduce((result, string, i) => {
        const value = values[i] ? `<mark>${values[i]}</mark>` : '';
        return result + string + value;
    }, '');
}

const sentence = highlight`Hello ${name}, you are ${age} years old`;
// "Hello <mark>John</mark>, you are <mark>30</mark> years old"
Enter fullscreen mode Exit fullscreen mode

Destructuring

// ARRAY DESTRUCTURING
const [first, second] = [1, 2, 3];
const [a, , c] = [1, 2, 3];           // Skip element
const [head, ...tail] = [1, 2, 3, 4]; // Rest
const [x = 10, y = 20] = [5];         // Defaults

// Swap variables
let a = 1, b = 2;
[a, b] = [b, a];

// OBJECT DESTRUCTURING
const { name, age } = { name: 'John', age: 30 };
const { name: userName, age: userAge } = person;  // Rename
const { city = 'Unknown' } = { name: 'John' };     // Default

// NESTED
const { address: { city, zip } } = user;

// REST
const { name, ...details } = person;

// FUNCTION PARAMETERS
function greet({ name, greeting = 'Hello' }) {
    return `${greeting}, ${name}!`;
}

greet({ name: 'John' });  // "Hello, John!"
Enter fullscreen mode Exit fullscreen mode

Modules

// EXPORTING (math.js)
// Named exports
export const PI = 3.14159;
export function add(a, b) {
    return a + b;
}

export class Calculator {
    multiply(a, b) {
        return a * b;
    }
}

// Default export
export default function greet(name) {
    return `Hello, ${name}!`;
}

// Re-export
export { foo, bar } from './other.js';

// IMPORTING (main.js)
// Default import
import greet from './math.js';

// Named imports
import { PI, add, Calculator } from './math.js';

// Import all as namespace
import * as math from './math.js';
console.log(math.PI);

// Aliases
import { add as sum } from './math.js';

// Dynamic imports
async function loadModule() {
    const module = await import('./math.js');
    console.log(module.add(2, 3));
}

// Conditional imports
if (condition) {
    const { feature } = await import('./feature.js');
}
Enter fullscreen mode Exit fullscreen mode

Classes

// CLASS DECLARATION
class Person {
    // Static property
    static species = 'Homo sapiens';

    // Private field
    #privateField = 'secret';

    // Public field
    publicField = 'public';

    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    // Method
    greet() {
        return `Hello, I'm ${this.name}`;
    }

    // Getter
    get info() {
        return `${this.name}, ${this.age} years old`;
    }

    // Setter
    set setAge(value) {
        if (value > 0) this.age = value;
    }

    // Private method
    #privateMethod() {
        return this.#privateField;
    }

    // Static method
    static isPerson(obj) {
        return obj instanceof Person;
    }
}

// INHERITANCE
class Employee extends Person {
    constructor(name, age, position) {
        super(name, age);
        this.position = position;
    }

    greet() {
        return `${super.greet()} - I work as ${this.position}`;
    }
}

// USAGE
const john = new Employee('John', 30, 'Developer');
console.log(john.greet());

// CHECK INSTANCE
console.log(john instanceof Employee);  // true
console.log(john instanceof Person);    // true

// CLASS EXPRESSIONS
const Animal = class {
    constructor(name) {
        this.name = name;
    }
};

// MIXINS
const Flyable = Base => class extends Base {
    fly() {
        console.log(`${this.name} is flying`);
    }
};

class Bird extends Flyable(Animal) {}
Enter fullscreen mode Exit fullscreen mode

Other ES6+ Features

// SPREAD OPERATOR
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];  // [1, 2, 3, 4, 5]

const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };  // { a: 1, b: 2, c: 3 }

// Function calls
const nums = [1, 2, 3];
Math.max(...nums);  // 3

// REST PARAMETERS
function sum(...numbers) {
    return numbers.reduce((a, b) => a + b, 0);
}

// NULLISH COALESCING (??)
const value = null ?? 'default';  // 'default'
const zero = 0 ?? 'default';      // 0 (not null/undefined)

// OPTIONAL CHAINING (?.)
const user = { profile: { name: 'John' } };
console.log(user?.profile?.name);    // 'John'
console.log(user?.settings?.theme);  // undefined

// LOGICAL ASSIGNMENT
let a = null;
a ??= 'default';  // a = a ?? 'default'

let b = 0;
b ||= 10;  // b = b || 10 (if falsy)

let c = 5;
c &&= 10;  // c = c && 10 (if truthy)

// NUMERIC SEPARATORS
const million = 1_000_000;
const binary = 0b1010_1010;

// BIGINT
const huge = 9007199254740991n;
const alsoHuge = BigInt(9007199254740991);

// PROMISE.ALLSETTLED
const promises = [fetch('/api/1'), fetch('/api/2')];
const results = await Promise.allSettled(promises);

// GLOBALTHIS
globalThis.setTimeout(() => {}, 1000);  // Works everywhere

// MATCHALL
const regex = /t(e)(st(\d?))/g;
const str = 'test1test2';
const matches = [...str.matchAll(regex)];

// DYNAMIC IMPORT
const module = await import('./module.js');

// TOP-LEVEL AWAIT (in modules)
const data = await fetch('/api/data').then(r => r.json());

// PRIVATE CLASS FIELDS
class Counter {
    #count = 0;

    increment() {
        this.#count++;
    }

    get #formatted() {  // Private getter
        return `Count: ${this.#count}`;
    }
}

// STATIC BLOCK
class Config {
    static settings;

    static {
        this.settings = loadSettings();
    }
}
Enter fullscreen mode Exit fullscreen mode

10. React 19 Complete

What is React?

Definition: React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It lets you compose complex UIs from small, isolated pieces of code called "components."

*Modern React Setup *

# ✅ RECOMMENDED: Vite (Fastest, most popular)
npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev

# With TypeScript
npm create vite@latest my-app -- --template react-ts

# ✅ Next.js 15 (Full-stack, App Router)
npx create-next-app@latest my-app

# Options:
# - TypeScript: Yes
# - ESLint: Yes  
# - Tailwind CSS: Yes
# - App Router: Yes (recommended)
# - Turbopack: Yes (for development speed)

# ✅ Remix
npx create-remix@latest my-app

# ❌ DEPRECATED - Do not use
npx create-react-app my-app  # Deprecated by React team
Enter fullscreen mode Exit fullscreen mode

JSX Fundamentals

// JSX is JavaScript XML - syntax extension for JavaScript

// BASIC JSX
function App() {
    const name = 'React';
    const element = <h1>Hello, {name}!</h1>;

    return element;
}

// EMBEDDING EXPRESSIONS
function Greeting() {
    const user = {
        firstName: 'John',
        lastName: 'Doe'
    };

    function formatName(user) {
        return `${user.firstName} ${user.lastName}`;
    }

    return <h1>Hello, {formatName(user)}!</h1>;
}

// JSX IS AN EXPRESSION
function getGreeting(user) {
    if (user) {
        return <h1>Hello, {user.name}!</h1>;
    }
    return <h1>Hello, Stranger.</h1>;
}

// SPECIFYING ATTRIBUTES
const element = <div className="container" tabIndex="0"></div>;
const element2 = <img src={user.avatarUrl} alt={user.name} />;

// CONDITIONAL RENDERING
function UserGreeting({ isLoggedIn }) {
    return (
        <div>
            {isLoggedIn ? (
                <h1>Welcome back!</h1>
            ) : (
                <h1>Please sign in.</h1>
            )}
        </div>
    );
}

// SHORT-CIRCUIT EVALUATION
function Mailbox({ unreadMessages }) {
    return (
        <div>
            <h1>Hello!</h1>
            {unreadMessages.length > 0 && (
                <p>You have {unreadMessages.length} unread messages.</p>
            )}
        </div>
    );
}

// NULLISH COALESCING
function UserName({ user }) {
    return <h1>{user?.name ?? 'Guest'}</h1>;
}

// LISTS & KEYS
function TodoList({ todos }) {
    return (
        <ul>
            {todos.map(todo => (
                <li key={todo.id}>
                    {todo.text}
                </li>
            ))}
        </ul>
    );
}

// FRAGMENTS
function Table() {
    return (
        <>
            <tr>
                <td>Row 1</td>
            </tr>
            <tr>
                <td>Row 2</td>
            </tr>
        </>
    );
}

// STYLE OBJECT
const styles = {
    color: 'red',
    backgroundColor: 'yellow',
    fontSize: '20px'
};

function StyledComponent() {
    return <div style={styles}>Styled content</div>;
}

// SPREAD ATTRIBUTES
function Component(props) {
    return <Child {...props} extra="value" />;
}
Enter fullscreen mode Exit fullscreen mode

Components

// FUNCTIONAL COMPONENT (Modern)
function Welcome({ name, age }) {
    return (
        <div className="welcome-card">
            <h1>Hello, {name}</h1>
            <p>You are {age} years old</p>
        </div>
    );
}

// DEFAULT PROPS
Welcome.defaultProps = {
    age: 18
};

// PROP TYPES (Runtime type checking)
import PropTypes from 'prop-types';

Welcome.propTypes = {
    name: PropTypes.string.isRequired,
    age: PropTypes.number
};

// COMPOSITION
function Card({ children, title, footer }) {
    return (
        <div className="card">
            <div className="card-header">
                <h2>{title}</h2>
            </div>
            <div className="card-body">
                {children}
            </div>
            {footer && (
                <div className="card-footer">
                    {footer}
                </div>
            )}
        </div>
    );
}

// USAGE
<Card 
    title="User Profile" 
    footer={<button>Save</button>}
>
    <p>John Doe</p>
    <p>john@example.com</p>
</Card>

// CONTAINMENT (children prop)
function SplitPane({ left, right }) {
    return (
        <div className="split-pane">
            <div className="pane-left">{left}</div>
            <div className="pane-right">{right}</div>
        </div>
    );
}

// SPECIALIZATION
function Dialog({ title, message }) {
    return (
        <Card title={title}>
            <p>{message}</p>
        </Card>
    );
}

// RENDER PROPS PATTERN
class MouseTracker extends React.Component {
    state = { x: 0, y: 0 };

    handleMouseMove = (event) => {
        this.setState({
            x: event.clientX,
            y: event.clientY
        });
    };

    render() {
        return (
            <div onMouseMove={this.handleMouseMove}>
                {this.props.render(this.state)}
            </div>
        );
    }
}

// USAGE
<MouseTracker render={({ x, y }) => (
    <p>Mouse position: {x}, {y}</p>
)} />
Enter fullscreen mode Exit fullscreen mode

React 19 New Features

// REACT 19 - NEW FEATURES

// 1. ACTIONS & useTransition
import { useTransition } from 'react';

function UpdateName() {
    const [name, setName] = useState('');
    const [error, setError] = useState(null);
    const [isPending, startTransition] = useTransition();

    const handleSubmit = () => {
        startTransition(async () => {
            const error = await updateName(name);
            if (error) {
                setError(error);
                return;
            }
            // Success
        });
    };

    return (
        <div>
            <input value={name} onChange={e => setName(e.target.value)} />
            <button onClick={handleSubmit} disabled={isPending}>
                {isPending ? 'Updating...' : 'Update'}
            </button>
            {error && <p>{error}</p>}
        </div>
    );
}

// 2. useActionState (replaces useFormState)
import { useActionState } from 'react';

function Form() {
    const [state, formAction, isPending] = useActionState(
        async (previousState, formData) => {
            const name = formData.get('name');
            await updateName(name);
            return { name };
        },
        { name: '' }
    );

    return (
        <form action={formAction}>
            <input name="name" defaultValue={state.name} />
            <button disabled={isPending}>Submit</button>
        </form>
    );
}

// 3. useOptimistic
import { useOptimistic } from 'react';

function Messages({ messages }) {
    const [optimisticMessages, addOptimisticMessage] = useOptimistic(
        messages,
        (state, newMessage) => [...state, { text: newMessage, sending: true }]
    );

    async function sendMessage(formData) {
        const message = formData.get('message');
        addOptimisticMessage(message);
        await deliverMessage(message);
    }

    return (
        <div>
            {optimisticMessages.map((msg, i) => (
                <div key={i} style={{ opacity: msg.sending ? 0.5 : 1 }}>
                    {msg.text}
                </div>
            ))}
            <form action={sendMessage}>
                <input name="message" />
                <button>Send</button>
            </form>
        </div>
    );
}

// 4. use (new hook for reading resources)
import { use } from 'react';

function Comments({ commentsPromise }) {
    const comments = use(commentsPromise);
    return comments.map(comment => <p key={comment.id}>{comment.text}</p>);
}

function Page({ commentsPromise }) {
    return (
        <Suspense fallback={<div>Loading comments...</div>}>
            <Comments commentsPromise={commentsPromise} />
        </Suspense>
    );
}

// 5. Server Components (Next.js App Router)
// ServerComponent.jsx (no 'use client')
async function ServerComponent() {
    const data = await fetch('https://api.example.com/data');
    const json = await data.json();

    return <div>{json.title}</div>;
}

// 6. Form Actions
function Form() {
    async function submitAction(formData) {
        'use server';
        await updateName(formData.get('name'));
    }

    return (
        <form action={submitAction}>
            <input name="name" />
            <button>Update</button>
        </form>
    );
}

// 7. Ref as Prop (no forwardRef needed)
function Input({ ref, ...props }) {
    return <input ref={ref} {...props} />;
}

// Usage
function Parent() {
    const inputRef = useRef(null);
    return <Input ref={inputRef} placeholder="Type here" />;
}

// 8. Context as Provider
const ThemeContext = createContext('light');

function App() {
    return (
        <ThemeContext value="dark">
            <Page />
        </ThemeContext>
    );
}

// 9. Document Metadata (Next.js)
export const metadata = {
    title: "'My Page',"
    description: 'Page description'
};

// 10. Asset Loading
import { preload, preinit, prefetchDNS } from 'react-dom';

function Component() {
    prefetchDNS('https://api.example.com');
    preload('https://example.com/font.woff2', { as: 'font' });
    preinit('https://example.com/script.js', { as: 'script' });

    return <div>Content</div>;
}
Enter fullscreen mode Exit fullscreen mode

11. React Hooks Deep Dive

useState Complete

import { useState } from 'react';

// BASIC USAGE
function Counter() {
    const [count, setCount] = useState(0);

    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={() => setCount(count + 1)}>Increment</button>
            <button onClick={() => setCount(count - 1)}>Decrement</button>
            <button onClick={() => setCount(0)}>Reset</button>
        </div>
    );
}

// OBJECT STATE
function UserForm() {
    const [user, setUser] = useState({
        name: '',
        email: '',
        age: 0
    });

    const updateField = (field, value) => {
        setUser(prev => ({
            ...prev,
            [field]: value
        }));
    };

    return (
        <form>
            <input 
                value={user.name}
                onChange={e => updateField('name', e.target.value)}
                placeholder="Name"
            />
            <input 
                value={user.email}
                onChange={e => updateField('email', e.target.value)}
                placeholder="Email"
            />
            <input 
                type="number"
                value={user.age}
                onChange={e => updateField('age', parseInt(e.target.value))}
                placeholder="Age"
            />
        </form>
    );
}

// ARRAY STATE
function TodoList() {
    const [todos, setTodos] = useState([]);

    const addTodo = (text) => {
        setTodos(prev => [...prev, {
            id: Date.now(),
            text,
            completed: false
        }]);
    };

    const toggleTodo = (id) => {
        setTodos(prev => prev.map(todo =>
            todo.id === id 
                ? { ...todo, completed: !todo.completed }
                : todo
        ));
    };

    const deleteTodo = (id) => {
        setTodos(prev => prev.filter(todo => todo.id !== id));
    };

    return (
        <div>
            {todos.map(todo => (
                <div key={todo.id}>
                    <input 
                        type="checkbox"
                        checked={todo.completed}
                        onChange={() => toggleTodo(todo.id)}
                    />
                    <span style={{ 
                        textDecoration: todo.completed ? 'line-through' : 'none' 
                    }}>
                        {todo.text}
                    </span>
                    <button onClick={() => deleteTodo(todo.id)}>Delete</button>
                </div>
            ))}
        </div>
    );
}

// FUNCTIONAL UPDATES (when new state depends on previous)
function Counter() {
    const [count, setCount] = useState(0);

    const incrementThreeTimes = () => {
        // ❌ Wrong: All use same count value
        // setCount(count + 1);
        // setCount(count + 1);
        // setCount(count + 1);

        // ✅ Correct: Each uses previous value
        setCount(c => c + 1);
        setCount(c => c + 1);
        setCount(c => c + 1);
    };

    return <button onClick={incrementThreeTimes}>+3</button>;
}

// LAZY INITIALIZATION
function ExpensiveComponent() {
    // Only runs once on initial render
    const [data, setData] = useState(() => {
        return computeExpensiveValue();
    });

    return <div>{data}</div>;
}

// MULTIPLE STATE VARIABLES
function Form() {
    const [name, setName] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');

    // Or use single object if they change together often
    const [form, setForm] = useState({
        name: '',
        email: '',
        password: ''
    });
}
Enter fullscreen mode Exit fullscreen mode

useEffect Complete

import { useEffect } from 'react';

// COMPONENT LIFECYCLE WITH useEffect

function Example() {
    // 1. RUN ON EVERY RENDER
    useEffect(() => {
        console.log('Every render');
    });

    // 2. RUN ONCE ON MOUNT (empty deps)
    useEffect(() => {
        console.log('Component mounted');

        // CLEANUP (runs on unmount)
        return () => {
            console.log('Component unmounting');
        };
    }, []);

    // 3. RUN WHEN DEPENDENCIES CHANGE
    const [count, setCount] = useState(0);

    useEffect(() => {
        console.log('Count changed:', count);
    }, [count]);

    // 4. MULTIPLE DEPENDENCIES
    const [name, setName] = useState('');

    useEffect(() => {
        console.log('Count or name changed');
    }, [count, name]);

    return <div>Example</div>;
}

// DATA FETCHING
function UserProfile({ userId }) {
    const [user, setUser] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        let cancelled = false;

        async function fetchUser() {
            setLoading(true);
            try {
                const response = await fetch(`/api/users/${userId}`);
                if (!response.ok) throw new Error('Failed to fetch');

                const data = await response.json();

                if (!cancelled) {
                    setUser(data);
                    setError(null);
                }
            } catch (err) {
                if (!cancelled) {
                    setError(err.message);
                }
            } finally {
                if (!cancelled) {
                    setLoading(false);
                }
            }
        }

        fetchUser();

        // Cleanup: prevent state update if unmounted
        return () => {
            cancelled = true;
        };
    }, [userId]);  // Re-fetch when userId changes

    if (loading) return <div>Loading...</div>;
    if (error) return <div>Error: {error}</div>;

    return <div>{user.name}</div>;
}

// SUBSCRIPTION PATTERN
function ChatRoom({ roomId }) {
    useEffect(() => {
        const connection = createConnection(roomId);
        connection.connect();

        return () => {
            connection.disconnect();
        };
    }, [roomId]);

    return <div>Chat Room: {roomId}</div>;
}

// EVENT LISTENER
function WindowSize() {
    const [size, setSize] = useState({
        width: window.innerWidth,
        height: window.innerHeight
    });

    useEffect(() => {
        const handleResize = () => {
            setSize({
                width: window.innerWidth,
                height: window.innerHeight
            });
        };

        window.addEventListener('resize', handleResize);

        return () => {
            window.removeEventListener('resize', handleResize);
        };
    }, []);

    return <div>{size.width} x {size.height}</div>;
}

// INTERVAL/ TIMEOUT
function Timer() {
    const [seconds, setSeconds] = useState(0);

    useEffect(() => {
        const interval = setInterval(() => {
            setSeconds(s => s + 1);
        }, 1000);

        return () => clearInterval(interval);
    }, []);

    return <div>Seconds: {seconds}</div>;
}

// useEffect vs useLayoutEffect
import { useEffect, useLayoutEffect } from 'react';

function Component() {
    // Runs AFTER browser paints (most cases)
    useEffect(() => {
        console.log('useEffect - after paint');
    });

    // Runs BEFORE browser paints (measure DOM, prevent flicker)
    useLayoutEffect(() => {
        console.log('useLayoutEffect - before paint');
        const { width } = ref.current.getBoundingClientRect();
        setWidth(width);
    });
}
Enter fullscreen mode Exit fullscreen mode

useContext

import { createContext, useContext, useState } from 'react';

// CREATE CONTEXT
const ThemeContext = createContext(null);

// PROVIDER COMPONENT
function ThemeProvider({ children }) {
    const [theme, setTheme] = useState('light');

    const toggleTheme = () => {
        setTheme(prev => prev === 'light' ? 'dark' : 'light');
    };

    const value = {
        theme,
        toggleTheme,
        isDark: theme === 'dark'
    };

    return (
        <ThemeContext.Provider value={value}>
            {children}
        </ThemeContext.Provider>
    );
}

// CUSTOM HOOK
function useTheme() {
    const context = useContext(ThemeContext);
    if (!context) {
        throw new Error('useTheme must be used within ThemeProvider');
    }
    return context;
}

// CONSUMER COMPONENT
function ThemedButton() {
    const { theme, toggleTheme, isDark } = useTheme();

    return (
        <button 
            onClick={toggleTheme}
            style={{
                background: isDark ? '#333' : '#fff',
                color: isDark ? '#fff' : '#333'
            }}
        >
            Current theme: {theme}
        </button>
    );
}

// USAGE
function App() {
    return (
        <ThemeProvider>
            <ThemedButton />
        </ThemeProvider>
    );
}

// MULTIPLE CONTEXTS
const UserContext = createContext(null);
const NotificationContext = createContext(null);

function App() {
    return (
        <UserContext.Provider value={user}>
            <NotificationContext.Provider value={notifications}>
                <Layout />
            </NotificationContext.Provider>
        </UserContext.Provider>
    );
}
Enter fullscreen mode Exit fullscreen mode

useRef

import { useRef } from 'react';

// DOM REFERENCE
function TextInput() {
    const inputRef = useRef(null);

    const focusInput = () => {
        inputRef.current.focus();
    };

    const getValue = () => {
        console.log(inputRef.current.value);
    };

    return (
        <div>
            <input ref={inputRef} type="text" />
            <button onClick={focusInput}>Focus</button>
            <button onClick={getValue}>Get Value</button>
        </div>
    );
}

// STORING MUTABLE VALUE (no re-render)
function Timer() {
    const [count, setCount] = useState(0);
    const intervalRef = useRef(null);

    const start = () => {
        if (intervalRef.current) return;

        intervalRef.current = setInterval(() => {
            setCount(c => c + 1);
        }, 1000);
    };

    const stop = () => {
        clearInterval(intervalRef.current);
        intervalRef.current = null;
    };

    return (
        <div>
            <p>{count}</p>
            <button onClick={start}>Start</button>
            <button onClick={stop}>Stop</button>
        </div>
    );
}

// PREVIOUS VALUE
function Counter() {
    const [count, setCount] = useState(0);
    const prevCountRef = useRef();

    useEffect(() => {
        prevCountRef.current = count;
    });

    return (
        <div>
            <p>Current: {count}</p>
            <p>Previous: {prevCountRef.current}</p>
            <button onClick={() => setCount(c => c + 1)}>+</button>
        </div>
    );
}

// FORWARDING REFS (React 19 - no forwardRef needed)
function Input({ ref, ...props }) {
    return <input ref={ref} {...props} />;
}

// MEASURING DOM
function MeasuredComponent() {
    const ref = useRef(null);
    const [height, setHeight] = useState(0);

    useLayoutEffect(() => {
        setHeight(ref.current.getBoundingClientRect().height);
    }, []);

    return (
        <div ref={ref}>
            <p>Height: {height}px</p>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

useReducer

import { useReducer } from 'react';

// INITIAL STATE
const initialState = {
    count: 0,
    step: 1,
    history: []
};

// REDUCER FUNCTION
function reducer(state, action) {
    switch (action.type) {
        case 'increment':
            return {
                ...state,
                count: state.count + state.step,
                history: [...state.history, state.count + state.step]
            };
        case 'decrement':
            return {
                ...state,
                count: state.count - state.step,
                history: [...state.history, state.count - state.step]
            };
        case 'setStep':
            return { ...state, step: action.payload };
        case 'reset':
            return initialState;
        default:
            throw new Error(`Unknown action: ${action.type}`);
    }
}

// USAGE
function Counter() {
    const [state, dispatch] = useReducer(reducer, initialState);

    return (
        <div>
            <p>Count: {state.count}</p>
            <p>Step: {state.step}</p>

            <button onClick={() => dispatch({ type: 'decrement' })}>
                -
            </button>
            <button onClick={() => dispatch({ type: 'increment' })}>
                +
            </button>

            <input 
                type="number"
                value={state.step}
                onChange={e => dispatch({ 
                    type: 'setStep', 
                    payload: Number(e.target.value) 
                })}
            />

            <button onClick={() => dispatch({ type: 'reset' })}>
                Reset
            </button>

            <p>History: {state.history.join(', ')}</p>
        </div>
    );
}

// COMPLEX EXAMPLE: TODO APP
const todoReducer = (state, action) => {
    switch (action.type) {
        case 'ADD':
            return [...state, {
                id: Date.now(),
                text: action.text,
                completed: false
            }];
        case 'TOGGLE':
            return state.map(todo =>
                todo.id === action.id 
                    ? { ...todo, completed: !todo.completed }
                    : todo
            );
        case 'DELETE':
            return state.filter(todo => todo.id !== action.id);
        default:
            return state;
    }
};
Enter fullscreen mode Exit fullscreen mode

useMemo & useCallback

import { useMemo, useCallback } from 'react';

// useMemo - CACHE EXPENSIVE CALCULATIONS
function ProductList({ products, filter }) {
    // Only recalculates when products or filter changes
    const filteredProducts = useMemo(() => {
        console.log('Filtering products...');
        return products.filter(p => 
            p.name.toLowerCase().includes(filter.toLowerCase())
        );
    }, [products, filter]);

    // Sort only when filtered products change
    const sortedProducts = useMemo(() => {
        return [...filteredProducts].sort((a, b) => 
            a.price - b.price
        );
    }, [filteredProducts]);

    return (
        <div>
            {sortedProducts.map(product => (
                <Product key={product.id} product={product} />
            ))}
        </div>
    );
}

// useCallback - CACHE FUNCTIONS
function Parent() {
    const [count, setCount] = useState(0);
    const [name, setName] = useState('');

    // Without useCallback: new function every render
    // With useCallback: same function unless deps change
    const handleClick = useCallback(() => {
        console.log('Clicked:', name);
    }, [name]);

    return (
        <div>
            <button onClick={() => setCount(c => c + 1)}>
                Count: {count}
            </button>
            <input value={name} onChange={e => setName(e.target.value)} />
            <Child onClick={handleClick} />
        </div>
    );
}

const Child = React.memo(({ onClick }) => {
    console.log('Child rendered');
    return <button onClick={onClick}>Click me</button>;
});

// WHEN TO USE
// useMemo: Expensive calculations, objects/arrays that cause re-renders
// useCallback: Functions passed to optimized children, useEffect dependencies
Custom Hooks
jsx
Copy
// useFetch.js
import { useState, useEffect } from 'react';

function useFetch(url) {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        let cancelled = false;

        async function fetchData() {
            try {
                setLoading(true);
                const response = await fetch(url);

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const json = await response.json();

                if (!cancelled) {
                    setData(json);
                    setError(null);
                }
            } catch (err) {
                if (!cancelled) {
                    setError(err.message);
                    setData(null);
                }
            } finally {
                if (!cancelled) {
                    setLoading(false);
                }
            }
        }

        fetchData();

        return () => {
            cancelled = true;
        };
    }, [url]);

    return { data, loading, error };
}

// Usage
function Users() {
    const { data, loading, error } = useFetch('/api/users');

    if (loading) return <div>Loading...</div>;
    if (error) return <div>Error: {error}</div>;

    return (
        <ul>
            {data.map(user => (
                <li key={user.id}>{user.name}</li>
            ))}
        </ul>
    );
}

// useLocalStorage.js
function useLocalStorage(key, initialValue) {
    const [value, setValue] = useState(() => {
        try {
            const item = localStorage.getItem(key);
            return item ? JSON.parse(item) : initialValue;
        } catch {
            return initialValue;
        }
    });

    useEffect(() => {
        localStorage.setItem(key, JSON.stringify(value));
    }, [key, value]);

    return [value, setValue];
}

// useDebounce.js
function useDebounce(value, delay) {
    const [debouncedValue, setDebouncedValue] = useState(value);

    useEffect(() => {
        const timer = setTimeout(() => {
            setDebouncedValue(value);
        }, delay);

        return () => clearTimeout(timer);
    }, [value, delay]);

    return debouncedValue;
}

// useWindowSize.js
function useWindowSize() {
    const [size, setSize] = useState({
        width: window.innerWidth,
        height: window.innerHeight
    });

    useEffect(() => {
        const handleResize = () => {
            setSize({
                width: window.innerWidth,
                height: window.innerHeight
            });
        };

        window.addEventListener('resize', handleResize);
        return () => window.removeEventListener('resize', handleResize);
    }, []);

    return size;
}

// useToggle.js
function useToggle(initial = false) {
    const [value, setValue] = useState(initial);

    const toggle = useCallback(() => setValue(v => !v), []);
    const setTrue = useCallback(() => setValue(true), []);
    const setFalse = useCallback(() => setValue(false), []);

    return [value, toggle, setTrue, setFalse];
}
Enter fullscreen mode Exit fullscreen mode

12. React Router v6

Setup & Basic Routing

import { 
    BrowserRouter, 
    Routes, 
    Route,
    Link,
    NavLink,
    useParams,
    useNavigate,
    useLocation,
    useSearchParams,
    Outlet,
    Navigate
} from 'react-router-dom';

function App() {
    return (
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<Layout />}>
                    <Route index element={<Home />} />
                    <Route path="about" element={<About />} />
                    <Route path="users/:id" element={<UserProfile />} />
                    <Route path="products" element={<Products />}>
                        <Route index element={<ProductList />} />
                        <Route path=":productId" element={<ProductDetail />} />
                    </Route>
                    <Route path="*" element={<NotFound />} />
                </Route>
            </Routes>
        </BrowserRouter>
    );
}

// LAYOUT WITH OUTLET
function Layout() {
    return (
        <div>
            <nav>
                <Link to="/">Home</Link>
                <Link to="/about">About</Link>
                <Link to="/products">Products</Link>
            </nav>

            <main>
                <Outlet />  {/* Child routes render here */}
            </main>

            <footer>Footer</footer>
        </div>
    );
}

// NAVIGATION
function Navigation() {
    const navigate = useNavigate();

    return (
        <nav>
            {/* Regular link */}
            <Link to="/">Home</Link>

            {/* NavLink with active state */}
            <NavLink 
                to="/about"
                className={({ isActive }) => isActive ? 'active' : ''}
                style={({ isActive }) => ({ 
                    color: isActive ? 'red' : 'black' 
                })}
            >
                About
            </NavLink>

            {/* Programmatic navigation */}
            <button onClick={() => navigate('/dashboard')}>
                Go to Dashboard
            </button>

            {/* Go back/forward */}
            <button onClick={() => navigate(-1)}>Back</button>
            <button onClick={() => navigate(1)}>Forward</button>

            {/* Replace history */}
            <button onClick={() => navigate('/login', { replace: true })}>
                Login (replace)
            </button>

            {/* With state */}
            <button onClick={() => navigate('/profile', { state: { from: 'home' } })}>
                Profile
            </button>
        </nav>
    );
}

// DYNAMIC ROUTES
function UserProfile() {
    const { id } = useParams();
    const location = useLocation();

    return (
        <div>
            <h1>User ID: {id}</h1>
            <p>Came from: {location.state?.from}</p>
        </div>
    );
}

// SEARCH PARAMETERS
function ProductList() {
    const [searchParams, setSearchParams] = useSearchParams();

    const category = searchParams.get('category');
    const sort = searchParams.get('sort') || 'name';

    const updateFilter = (newCategory) => {
        setSearchParams({ category: newCategory, sort });
    };

    return (
        <div>
            <p>Category: {category}</p>
            <p>Sort: {sort}</p>
            <button onClick={() => updateFilter('electronics')}>
                Electronics
            </button>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

Protected Routes

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

function ProtectedRoute({ children }) {
    const isAuthenticated = useAuth();
    const location = useLocation();

    if (!isAuthenticated) {
        // Redirect to login, save location
        return <Navigate to="/login" state={{ from: location }} replace />;
    }

    return children;
}

// USAGE
<Route 
    path="/dashboard" 
    element={
        <ProtectedRoute>
            <Dashboard />
        </ProtectedRoute>
    } 
/>

// ROLE-BASED ACCESS
function RoleRoute({ children, allowedRoles }) {
    const { user } = useAuth();

    if (!allowedRoles.includes(user.role)) {
        return <Navigate to="/unauthorized" replace />;
    }

    return children;
}

// LOGIN REDIRECT
function Login() {
    const navigate = useNavigate();
    const location = useLocation();

    const handleLogin = async (credentials) => {
        const success = await login(credentials);
        if (success) {
            const from = location.state?.from?.pathname || '/dashboard';
            navigate(from, { replace: true });
        }
    };
}
Enter fullscreen mode Exit fullscreen mode

Data Loading (React Router 6.4+)

import { 
    createBrowserRouter, 
    RouterProvider,
    useLoaderData,
    useActionData,
    Form
} from 'react-router-dom';

// LOADER
async function userLoader({ params }) {
    const response = await fetch(`/api/users/${params.id}`);
    if (!response.ok) {
        throw new Response('Not Found', { status: 404 });
    }
    return response.json();
}

// ACTION
async function updateUserAction({ request, params }) {
    const formData = await request.formData();
    const updates = Object.fromEntries(formData);

    const response = await fetch(`/api/users/${params.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(updates)
    });

    if (!response.ok) {
        return { error: 'Failed to update' };
    }

    return { success: true };
}

// ROUTER CONFIG
const router = createBrowserRouter([
    {
        path: '/',
        element: <Layout />,
        children: [
            {
                path: 'users/:id',
                element: <UserProfile />,
                loader: userLoader,
                action: updateUserAction
            }
        ]
    }
]);

function App() {
    return <RouterProvider router={router} />;
}

// COMPONENT USING LOADER
function UserProfile() {
    const user = useLoaderData();
    const actionData = useActionData();

    return (
        <div>
            <h1>{user.name}</h1>

            {actionData?.error && (
                <p className="error">{actionData.error}</p>
            )}

            <Form method="post">
                <input name="name" defaultValue={user.name} />
                <button type="submit">Update</button>
            </Form>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

13. Next.js 15 Complete

What is Next.js?

Definition: Next.js is a React framework that provides server-side rendering, static site generation, API routes, and optimized production builds with minimal configuration.
Installation & Setup

# Create Next.js 15 project
npx create-next-app@latest my-app

# Options during setup:
# - TypeScript: Yes
# - ESLint: Yes
# - Tailwind CSS: Yes (recommended)
# - src/ directory: No (or Yes)
# - App Router: Yes (recommended)
# - Turbopack: Yes (for dev speed)
# - Import alias: @/*

cd my-app
npm run dev  # Starts dev server on http://localhost:3000
Enter fullscreen mode Exit fullscreen mode

App Router File Structure

my-app/
├── app/                    # App Router (Next.js 13+)
│   ├── layout.tsx         # Root layout
│   ├── page.tsx           # Home page (/)
│   ├── loading.tsx        # Loading UI
│   ├── error.tsx          # Error boundary
│   ├── not-found.tsx      # 404 page
│   ├── template.tsx       # Re-mounts on navigation
│   ├── globals.css        # Global styles
│   │
│   ├── about/
│   │   └── page.tsx       # /about
│   │
│   ├── blog/
│   │   ├── page.tsx       # /blog
│   │   ├── loading.tsx    # Blog loading state
│   │   └── [slug]/
│   │       └── page.tsx   # /blog/my-post (dynamic)
│   │
│   ├── (marketing)/       # Route group (no URL segment)
│   │   ├── layout.tsx     # Shared marketing layout
│   │   ├── pricing/
│   │   └── features/
│   │
│   ├── dashboard/
│   │   ├── layout.tsx     # Dashboard layout
│   │   ├── page.tsx       # /dashboard
│   │   ├── settings/
│   │   │   └── page.tsx   # /dashboard/settings
│   │   └── @team/         # Parallel route
│   │
│   └── api/               # API routes
│       └── users/
│           └── route.ts   # /api/users
│
├── components/            # React components
│   ├── ui/               # UI components
│   └── shared/           # Shared components
│
├── lib/                   # Utilities
│   └── utils.ts
│
├── hooks/                 # Custom hooks
├── types/                 # TypeScript types
├── public/                # Static files
├── styles/                # Additional styles
├── next.config.js         # Next.js config
└── middleware.ts          # Edge middleware
Enter fullscreen mode Exit fullscreen mode

Server vs Client Components

// app/page.tsx - SERVER COMPONENT (default)
// No 'use client' directive = Server Component

async function getData() {
    const res = await fetch('https://api.example.com/posts', {
        // Caching strategies
        cache: 'force-cache'           // Static (default)
        // cache: 'no-store'            // Dynamic
        // next: { revalidate: 60 }     // ISR: revalidate every 60s
        // next: { tags: ['posts'] }    // On-demand revalidation
    });

    if (!res.ok) throw new Error('Failed to fetch');
    return res.json();
}

export default async function HomePage() {
    const posts = await getData();

    return (
        <main>
            <h1>Latest Posts</h1>
            {posts.map(post => (
                <article key={post.id}>
                    <h2>{post.title}</h2>
                    <p>{post.excerpt}</p>
                </article>
            ))}
        </main>
    );
}

// components/Counter.tsx - CLIENT COMPONENT
'use client';  // Must be first line

import { useState } from 'react';

export default function Counter() {
    const [count, setCount] = useState(0);

    return (
        <button onClick={() => setCount(c => c + 1)}>
            Count: {count}
        </button>
    );
}

// INTERLEAVING: Server Component imports Client Component
import Counter from '@/components/Counter';

export default async function Page() {
    const data = await getData();

    return (
        <div>
            <h1>{data.title}</h1>  {/* Server-rendered */}
            <Counter />            {/* Client interactivity */}
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

Data Fetching Patterns

// 1. SERVER COMPONENTS (Recommended)
async function getUser(id: string) {
    const res = await fetch(`https://api.example.com/users/${id}`);
    return res.json();
}

export default async function UserPage({ params }: { params: { id: string } }) {
    const user = await getUser(params.id);
    return <div>{user.name}</div>;
}

// 2. STATIC SITE GENERATION (SSG)
export async function generateStaticParams() {
    const posts = await fetch('https://api.example.com/posts').then(r => r.json());

    return posts.map((post: any) => ({
        slug: post.slug
    }));
}

// 3. INCREMENTAL STATIC REGENERATION (ISR)
async function getProducts() {
    const res = await fetch('https://api.example.com/products', {
        next: { revalidate: 3600 }  // Revalidate every hour
    });
    return res.json();
}

// 4. ON-DEMAND REVALIDATION
// app/api/revalidate/route.ts
import { revalidateTag } from 'next/cache';
import { NextRequest } from 'next/server';

export async function POST(request: NextRequest) {
    const tag = request.nextUrl.searchParams.get('tag');
    revalidateTag(tag);
    return Response.json({ revalidated: true, now: Date.now() });
}

// 5. PARALLEL DATA FETCHING
export default async function Dashboard() {
    // Fetch in parallel
    const [user, orders, notifications] = await Promise.all([
        fetch('/api/user').then(r => r.json()),
        fetch('/api/orders').then(r => r.json()),
        fetch('/api/notifications').then(r => r.json())
    ]);

    return <DashboardUI user={user} orders={orders} notifications={notifications} />;
}

// 6. STREAMING WITH SUSPENSE
import { Suspense } from 'react';

export default function Page() {
    return (
        <div>
            <h1>Dashboard</h1>

            <Suspense fallback={<Skeleton />}>
                <UserProfile />
            </Suspense>

            <Suspense fallback={<Skeleton />}>
                <RecentOrders />
            </Suspense>
        </div>
    );
}

async function UserProfile() {
    const user = await fetch('/api/user').then(r => r.json());
    return <div>{user.name}</div>;
}
Enter fullscreen mode Exit fullscreen mode

API Routes

// app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server';

// GET /api/users
export async function GET(request: NextRequest) {
    const { searchParams } = new URL(request.url);
    const page = searchParams.get('page') || '1';

    const users = await db.query('SELECT * FROM users LIMIT 10 OFFSET ?', [
        (parseInt(page) - 1) * 10
    ]);

    return NextResponse.json(users);
}

// POST /api/users
export async function POST(request: NextRequest) {
    try {
        const body = await request.json();

        // Validation
        if (!body.name || !body.email) {
            return NextResponse.json(
                { error: 'Name and email required' },
                { status: 400 }
            );
        }

        const user = await db.query(
            'INSERT INTO users (name, email) VALUES (?, ?)',
            [body.name, body.email]
        );

        return NextResponse.json(user, { status: 201 });
    } catch (error) {
        return NextResponse.json(
            { error: 'Failed to create user' },
            { status: 500 }
        );
    }
}

// DYNAMIC ROUTE: app/api/users/[id]/route.ts
import { NextRequest, NextResponse } from 'next/server';

interface RouteParams {
    params: { id: string };
}

export async function GET(request: NextRequest, { params }: RouteParams) {
    const user = await db.query('SELECT * FROM users WHERE id = ?', [params.id]);

    if (!user) {
        return NextResponse.json({ error: 'User not found' }, { status: 404 });
    }

    return NextResponse.json(user);
}

export async function PUT(request: NextRequest, { params }: RouteParams) {
    const body = await request.json();
    const updated = await db.query(
        'UPDATE users SET name = ?, email = ? WHERE id = ?',
        [body.name, body.email, params.id]
    );
    return NextResponse.json(updated);
}

export async function DELETE(request: NextRequest, { params }: RouteParams) {
    await db.query('DELETE FROM users WHERE id = ?', [params.id]);
    return NextResponse.json({ message: 'Deleted' });
}

// EDGE RUNTIME
export const runtime = 'edge';

export async function GET(request: NextRequest) {
    // Runs at edge locations globally
    const country = request.geo?.country;
    return NextResponse.json({ country });
}
Enter fullscreen mode Exit fullscreen mode

Next.js 15 New Features

// 1. PARTIAL PRERENDERING (PPR) - Experimental
// next.config.js
module.exports = {
    experimental: {
        ppr: true
    }
};

// Components can be partially static, partially dynamic
export default async function Page() {
    return (
        <div>
            <StaticHeader />  {/* Prerendered */}
            <DynamicContent /> {/* Streamed */}
        </div>
    );
}

// 2. SERVER ACTIONS (Stable)
// app/actions.ts
'use server';

import { revalidatePath } from 'next/cache';

export async function createTodo(formData: FormData) {
    const title = formData.get('title');

    await db.query('INSERT INTO todos (title) VALUES (?)', [title]);

    revalidatePath('/todos');
}

// app/page.tsx
import { createTodo } from './actions';

export default function Page() {
    return (
        <form action={createTodo}>
            <input name="title" />
            <button type="submit">Add Todo</button>
        </form>
    );
}

// 3. TURBOPACK (Dev mode)
// next.config.js
module.exports = {
    turbo: {
        rules: {
            '*.svg': {
                loaders: ['@svgr/webpack'],
                as: '*.js'
            }
        }
    }
};

// 4. IMAGE COMPONENT IMPROVEMENTS
import Image from 'next/image';

export default function Page() {
    return (
        <Image
            src="/photo.jpg"
            alt="Photo"
            width={800}
            height={600}
            priority          // Preload critical images
            placeholder="blur"
            blurDataURL="data:image/jpeg;base64,..."
            quality={75}      // 0-100
            fill              // Fill parent container
            sizes="(max-width: 768px) 100vw, 50vw"
        />
    );
}

// 5. FONT OPTIMIZATION
import { Inter, Roboto } from 'next/font/google';

const inter = Inter({ 
    subsets: ['latin'],
    display: 'swap',
    variable: '--font-inter'
});

const roboto = Roboto({
    weight: ['400', '700'],
    subsets: ['latin']
});

export default function RootLayout({ children }) {
    return (
        <html lang="en" className={inter.variable}>
            <body className={roboto.className}>{children}</body>
        </html>
    );
}

// 6. METADATA API
import type { Metadata } from 'next';

export const metadata: Metadata = {
    title: "{"
        default: 'My Site',
        template: '%s | My Site'
    },
    description: "'A great website',"
    keywords: ['nextjs', 'react'],
    authors: [{ name: 'John' }],
    openGraph: {
        title: "'My Site',"
        description: "'Description',"
        type: 'website'
    },
    twitter: {
        card: 'summary_large_image'
    },
    robots: {
        index: true,
        follow: true
    }
};

// Dynamic metadata
export async function generateMetadata({ params }): Promise<Metadata> {
    const product = await getProduct(params.id);

    return {
        title: "product.name,"
        description: "product.description"
    };
}
Enter fullscreen mode Exit fullscreen mode

14. State Management

Context API Guide

  1. Core Concepts
// Context solves "prop drilling" - passing data through many component layers

// BEFORE: Prop drilling hell
function App() {
  const [user, setUser] = useState(null);
  return <Layout user={user} setUser={setUser} />; // Pass down...
}

function Layout({ user, setUser }) {
  return <Header user={user} setUser={setUser} />; // Keep passing...
}

function Header({ user, setUser }) {
  return <UserMenu user={user} setUser={setUser} />; // Still passing!
}

// AFTER: Context - direct access anywhere in the tree
function UserMenu() {
  const { user, setUser } = useUser(); // Direct access! 🎉
}
Enter fullscreen mode Exit fullscreen mode
  1. Basic Implementation
// contexts/UserContext.jsx
import { createContext, useContext, useState } from 'react';

// 1. CREATE CONTEXT
const UserContext = createContext(null);

// 2. PROVIDER COMPONENT
export function UserProvider({ children }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(false);

  const login = async (credentials) => {
    setLoading(true);
    const response = await fetch('/api/login', {
      method: 'POST',
      body: JSON.stringify(credentials)
    });
    const data = await response.json();
    setUser(data.user);
    setLoading(false);
  };

  const logout = () => setUser(null);

  // Value object contains state AND functions
  const value = {
    user,
    loading,
    login,
    logout,
    isAuthenticated: !!user
  };

  return (
    <UserContext.Provider value={value}>
      {children}
    </UserContext.Provider>
  );
}

// 3. CUSTOM HOOK (essential pattern!)
export function useUser() {
  const context = useContext(UserContext);
  if (context === null) {
    throw new Error('useUser must be used within UserProvider');
  }
  return context;
}

// 4. USAGE
function App() {
  return (
    <UserProvider>
      <Layout />
    </UserProvider>
  );
}

function UserProfile() {
  const { user, logout } = useUser(); // Clean API!

  return (
    <div>
      <h1>Welcome, {user.name}</h1>
      <button onClick={logout}>Logout</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
  1. Multiple Contexts Pattern
// contexts/index.js - Combine multiple contexts cleanly

import { ThemeProvider } from './ThemeContext';
import { UserProvider } from './UserContext';
import { NotificationProvider } from './NotificationContext';

// Compose providers (avoid nesting hell)
export function AppProviders({ children }) {
  return (
    <ThemeProvider>
      <UserProvider>
        <NotificationProvider>
          {children}
        </NotificationProvider>
      </UserProvider>
    </ThemeProvider>
  );
}

// Or use a helper
function composeProviders(...providers) {
  return ({ children }) =>
    providers.reduceRight(
      (acc, Provider) => <Provider>{acc}</Provider>,
      children
    );
}

export const AppProviders = composeProviders(
  ThemeProvider,
  UserProvider,
  NotificationProvider
);
Enter fullscreen mode Exit fullscreen mode
  1. Performance Optimization (The "Context Splitting" Pattern) The Problem: All consumers re-render when ANY value changes
// ❌ BAD: Everything re-renders when theme changes
function BadProvider({ children }) {
  const [theme, setTheme] = useState('light');
  const [user, setUser] = useState(null); // Unrelated state!

  return (
    <Context.Provider value={{ theme, setTheme, user, setUser }}>
      {children}
    </Context.Provider>
  );
}
Enter fullscreen mode Exit fullscreen mode

Solutions

// ✅ SOLUTION 1: Split into separate contexts
const ThemeContext = createContext(null);
const UserContext = createContext(null);

function App() {
  return (
    <ThemeProvider>
      <UserProvider>
        <AppContent />
      </UserProvider>
    </ThemeProvider>
  );
}

// Components subscribe only to what they need
function ThemedButton() {
  const { theme } = useTheme(); // Only re-renders on theme changes
}

function UserAvatar() {
  const { user } = useUser(); // Only re-renders on user changes
}
Enter fullscreen mode Exit fullscreen mode
// ✅ SOLUTION 2: useMemo for stable references
function BetterProvider({ children }) {
  const [theme, setTheme] = useState('light');

  // Memoize the value object
  const value = useMemo(() => ({
    theme,
    setTheme
  }), [theme]); // Only recreate when theme changes

  return (
    <ThemeContext.Provider value={value}>
      {children}
    </ThemeContext.Provider>
  );
}
Enter fullscreen mode Exit fullscreen mode

// ✅ SOLUTION 3: State colocation (React 18+)
// Keep state as close to where it's used as possible
// Don't put everything in global context!
Enter fullscreen mode Exit fullscreen mode
  1. Advanced Patterns
// PATTERN: Context with Reducer (like Redux but built-in)
const CartContext = createContext(null);

function cartReducer(state, action) {
  switch (action.type) {
    case 'ADD_ITEM':
      return { ...state, items: [...state.items, action.payload] };
    case 'REMOVE_ITEM':
      return { ...state, items: state.items.filter(i => i.id !== action.payload) };
    case 'CLEAR':
      return { items: [], total: 0 };
    default:
      return state;
  }
}

export function CartProvider({ children }) {
  const [state, dispatch] = useReducer(cartReducer, { items: [], total: 0 });

  // Memoize actions to prevent re-renders
  const actions = useMemo(() => ({
    addItem: (item) => dispatch({ type: 'ADD_ITEM', payload: item }),
    removeItem: (id) => dispatch({ type: 'REMOVE_ITEM', payload: id }),
    clear: () => dispatch({ type: 'CLEAR' })
  }), []);

  const value = useMemo(() => ({
    ...state,
    ...actions
  }), [state, actions]);

  return (
    <CartContext.Provider value={value}>
      {children}
    </CartContext.Provider>
  );
}
Enter fullscreen mode Exit fullscreen mode
// PATTERN: Compound Components with Context
const TabsContext = createContext(null);

function Tabs({ children, defaultTab }) {
  const [activeTab, setActiveTab] = useState(defaultTab);

  return (
    <TabsContext.Provider value={{ activeTab, setActiveTab }}>
      <div className="tabs">{children}</div>
    </TabsContext.Provider>
  );
}

function TabList({ children }) {
  return <div className="tab-list">{children}</div>;
}

function Tab({ value, children }) {
  const { activeTab, setActiveTab } = useContext(TabsContext);

  return (
    <button
      className={activeTab === value ? 'active' : ''}
      onClick={() => setActiveTab(value)}
    >
      {children}
    </button>
  );
}

function TabPanel({ value, children }) {
  const { activeTab } = useContext(TabsContext);
  if (value !== activeTab) return null;
  return <div className="tab-panel">{children}</div>;
}

// Usage - clean, semantic API
<Tabs defaultTab="account">
  <TabList>
    <Tab value="account">Account</Tab>
    <Tab value="security">Security</Tab>
  </TabList>
  <TabPanel value="account">Account settings...</TabPanel>
  <TabPanel value="security">Security settings...</TabPanel>
</Tabs>
Enter fullscreen mode Exit fullscreen mode

Redux Toolkit (Modern Redux)

npm install @reduxjs/toolkit react-redux
Enter fullscreen mode Exit fullscreen mode
// store/store.ts
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './slices/counterSlice';
import userReducer from './slices/userSlice';

export const store = configureStore({
    reducer: {
        counter: counterReducer,
        user: userReducer
    },
    middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware({
            serializableCheck: {
                ignoredActions: ['persist/PERSIST']
            }
        })
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

// App.tsx
import { Provider } from 'react-redux';
import { store } from './store/store';

function App() {
    return (
        <Provider store={store}>
            <YourApp />
        </Provider>
    );
}

// store/slices/counterSlice.ts
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';

interface CounterState {
    value: number;
    loading: boolean;
}

const initialState: CounterState = {
    value: 0,
    loading: false
};

// Async thunk
export const incrementAsync = createAsyncThunk(
    'counter/incrementAsync',
    async (amount: number) => {
        await new Promise(resolve => setTimeout(resolve, 1000));
        return amount;
    }
);

const counterSlice = createSlice({
    name: 'counter',
    initialState,
    reducers: {
        increment: (state) => {
            state.value += 1;
        },
        decrement: (state) => {
            state.value -= 1;
        },
        incrementByAmount: (state, action: PayloadAction<number>) => {
            state.value += action.payload;
        }
    },
    extraReducers: (builder) => {
        builder
            .addCase(incrementAsync.pending, (state) => {
                state.loading = true;
            })
            .addCase(incrementAsync.fulfilled, (state, action) => {
                state.loading = false;
                state.value += action.payload;
            });
    }
});

export const { increment, decrement, incrementByAmount } = counterSlice.actions;
export default counterSlice.reducer;

// hooks.ts (Typed hooks)
import { useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from './store';

export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

// Component usage
import { useAppDispatch, useAppSelector } from '@/store/hooks';

function Counter() {
    const count = useAppSelector((state: RootState) => state.counter.value);
    const dispatch = useAppDispatch();

    return (
        <div>
            <p>{count}</p>
            <button onClick={() => dispatch(increment())}>+</button>
            <button onClick={() => dispatch(incrementAsync(5))}>
                +5 (async)
            </button>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

Zustand (Lightweight Alternative)

npm install zustand
Enter fullscreen mode Exit fullscreen mode
// store/useStore.ts
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';

interface BearState {
    bears: number;
    increase: () => void;
    decrease: () => void;
    removeAllBears: () => void;
}

export const useBearStore = create<BearState>()(
    immer(
        persist(
            (set) => ({
                bears: 0,
                increase: () => set((state) => { state.bears += 1 }),
                decrease: () => set((state) => { state.bears -= 1 }),
                removeAllBears: () => set({ bears: 0 })
            }),
            {
                name: 'bear-storage'
            }
        )
    )
);

// Usage
function BearCounter() {
    const bears = useBearStore((state) => state.bears);
    const increase = useBearStore((state) => state.increase);

    return (
        <div>
            <h1>{bears} bears</h1>
            <button onClick={increase}>Add bear</button>
        </div>
    );
}

// With selectors (prevents unnecessary re-renders)
const useUserStore = create((set) => ({
    firstName: '',
    lastName: '',
    updateFirstName: (firstName) => set({ firstName }),
    updateLastName: (lastName) => set({ lastName })
}));

// Component only re-renders when firstName changes
function FirstName() {
    const firstName = useUserStore((state) => state.firstName);
    return <div>{firstName}</div>;
}
Enter fullscreen mode Exit fullscreen mode

React Query (TanStack Query)

npm install @tanstack/react-query
Enter fullscreen mode Exit fullscreen mode
// providers.tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';

const queryClient = new QueryClient({
    defaultOptions: {
        queries: {
            staleTime: 60 * 1000,  // 1 minute
            refetchOnWindowFocus: false
        }
    }
});

export function Providers({ children }) {
    return (
        <QueryClientProvider client={queryClient}>
            {children}
            <ReactQueryDevtools initialIsOpen={false} />
        </QueryClientProvider>
    );
}

// hooks/useUsers.ts
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';

export function useUsers() {
    return useQuery({
        queryKey: ['users'],
        queryFn: async () => {
            const res = await fetch('/api/users');
            return res.json();
        }
    });
}

export function useCreateUser() {
    const queryClient = useQueryClient();

    return useMutation({
        mutationFn: async (newUser) => {
            const res = await fetch('/api/users', {
                method: 'POST',
                body: JSON.stringify(newUser)
            });
            return res.json();
        },
        onSuccess: () => {
            // Invalidate and refetch
            queryClient.invalidateQueries({ queryKey: ['users'] });
        }
    });
}

// Component usage
function Users() {
    const { data, isLoading, error } = useUsers();
    const createUser = useCreateUser();

    if (isLoading) return <div>Loading...</div>;

    return (
        <div>
            {data.map(user => (
                <div key={user.id}>{user.name}</div>
            ))}

            <button 
                onClick={() => createUser.mutate({ name: 'New User' })}
                disabled={createUser.isPending}
            >
                Add User
            </button>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

*When to Use What? *

State Management Decision Guide

Scenario Solution Why
Theme, Locale, Auth Context Low update frequency, truly global
Complex app state Redux / Zustand DevTools, middleware, time-travel
Server state React Query Caching, synchronization, deduping
Form state React Hook Form Performance, validation, focus management
UI state (modals, toasts) Context or Zustand Simple, local to feature
High-frequency updates External library Context re-render performance

State Management Tool Tiers

Tier Tool Use Case
Built-in Context API Theme, auth, locale, dependency injection
Lightweight Zustand Simple global state, avoids Context boilerplate
Full-featured Redux Toolkit Complex state logic, team collaboration
Server State React Query API data caching, synchronization

15. Performance Optimization

React Optimization Techniques

// 1. REACT.MEMO - Prevent unnecessary re-renders
const ExpensiveComponent = React.memo(function MyComponent({ data }) {
    // Only re-renders if data changes
    return <div>{data}</div>;
}, (prevProps, nextProps) => {
    // Custom comparison
    return prevProps.id === nextProps.id;
});

// 2. USEMEMO - Cache expensive calculations
function ProductList({ products, filter }) {
    const filtered = useMemo(() => {
        return products.filter(p => 
            p.name.toLowerCase().includes(filter.toLowerCase())
        );
    }, [products, filter]);

    return <div>{filtered.map(p => <Product key={p.id} product={p} />)}</div>;
}

// 3. USECALLBACK - Cache function references
function Parent() {
    const [count, setCount] = useState(0);

    const handleClick = useCallback(() => {
        console.log('Clicked');
    }, []);

    return <Child onClick={handleClick} />;
}

const Child = React.memo(({ onClick }) => {
    return <button onClick={onClick}>Click</button>;
});

// 4. CODE SPLITTING & LAZY LOADING
import { lazy, Suspense } from 'react';

const HeavyComponent = lazy(() => import('./HeavyComponent'));

function App() {
    return (
        <Suspense fallback={<div>Loading...</div>}>
            <HeavyComponent />
        </Suspense>
    );
}

// 5. VIRTUALIZATION (react-window)
import { FixedSizeList } from 'react-window';

function VirtualList({ items }) {
    const Row = ({ index, style }) => (
        <div style={style}>{items[index].name}</div>
    );

    return (
        <FixedSizeList
            height={500}
            itemCount={items.length}
            itemSize={35}
            width="100%"
        >
            {Row}
        </FixedSizeList>
    );
}

// 6. IMAGE OPTIMIZATION
import Image from 'next/image';

function Gallery() {
    return (
        <Image
            src="/photo.jpg"
            alt="Photo"
            width={800}
            height={600}
            loading="lazy"
            placeholder="blur"
            blurDataURL="data:image/jpeg;base64,..."
        />
    );
}

// 7. PRELOAD CRITICAL RESOURCES
import Head from 'next/head';

function Page() {
    return (
        <>
            <Head>
                <link rel="preload" href="/critical.css" as="style" />
                <link rel="preconnect" href="https://fonts.googleapis.com" />
            </Head>
            <Content />
        </>
    );
}
Enter fullscreen mode Exit fullscreen mode

Core Web Vitals Optimization

// next.config.js
module.exports = {
    // Image optimization
    images: {
        formats: ['image/avif', 'image/webp'],
        remotePatterns: [
            {
                protocol: 'https',
                hostname: 'cdn.example.com'
            }
        ]
    },

    // Compression
    compress: true,

    // Script optimization
    experimental: {
        nextScriptWorkers: true
    },

    // Bundle analyzer (when needed)
    webpack: (config, { isServer }) => {
        if (process.env.ANALYZE === 'true') {
            const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
            config.plugins.push(new BundleAnalyzerPlugin());
        }
        return config;
    }
};
Enter fullscreen mode Exit fullscreen mode

Quick Reference
Modern Frontend Stack 2026

Category Technology Purpose
Build Tool Vite / Next.js Fast development & production builds
Framework React 19 / Next.js 15 UI components & full-stack
Styling Tailwind CSS Utility-first CSS
State Zustand / Redux Toolkit / React Query State management
Forms React Hook Form Form handling
Validation Zod Schema validation
Animation Framer Motion React animations
Testing Vitest + React Testing Library Unit & integration tests
Type Safety TypeScript Static type checking

Essential VS Code Extensions

  • ES7+ React/Redux/React-Native snippets
  • Tailwind CSS IntelliSense
  • Prettier - Code: formatter
  • ESLint
  • Auto Rename Tag
  • GitLens
  • Thunder Client (API testing)

Browser DevTools Tips

// Console utilities
$_              // Last result
$0, $1, $2      // Last selected elements
$$('div')       // Query selector all
copy(object)    // Copy to clipboard
inspect(element) // Inspect element
monitorEvents(window, 'resize') // Monitor events

// Performance
console.time('label');
// ... code
console.timeEnd('label');

console.table(data);

// Network throttling for testing
// DevTools > Network > Throttling > Slow 3G
Enter fullscreen mode Exit fullscreen mode

This guide covers everything you need for modern frontend development in 2026. You've learned HTML, CSS, JavaScript, React, Next.js, and how to connect everything with a MERN stack.

But remember, web development never stops changing. New tools appear, frameworks update, and better ways of doing things emerge constantly. What you've learned here is your foundation—the core concepts that will help you adapt to whatever comes next.

The real learning happens when you start building. Pick a project idea, start coding, make mistakes, fix them, and learn from the process. Your first project won't be perfect, and that's completely fine. Every developer started exactly where you are now.

Keep practicing, stay curious, and don't be afraid to experiment. The web community is huge and helpful—use it. Read documentation, watch tutorials, join developer communities, and most importantly, keep building.
Your frontend development journey starts here, but where it goes is entirely up to you.

Happy coding!
May your code be clean, your bugs be few, and your applications run smoothly.

Top comments (0)