Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Next-js

Learn Next-js - 9 Code Examples & CST Typing Practice Test

Next.js is a powerful React framework for building modern full-stack web applications with features like server-side rendering, static generation, routing, API endpoints, and server components. It emphasizes performance, scalability, and developer experience.

View all 9 Next-js code examples →
Next.js Counter with useStateNext.js Counter with useEffect and localStorageNext.js Counter using useReducerNext.js Counter with ContextNext.js Counter with TypeScriptNext.js Counter with Inline StylesNext.js Counter with Buttons MapNext.js Counter with useMemoNext.js Counter with Custom Hook

Learn NEXT-JS with Real Code Examples

Updated Nov 21, 2025

Explain

Next.js helps developers build production-ready React applications with routing and rendering handled out of the box.

It provides hybrid rendering models like SSR, SSG, ISR, and RSC.

Next.js is optimized for performance, scalability, and full-stack React development.

Core Features

Server Components by default

Dynamic and static routing

Layouts and nested routing

Next.js API routes for backend logic

Middleware for edge functions

Basic Concepts Overview

Server vs Client components

Layouts and nested routes

Rendering models (SSR, SSG, ISR)

API routes and server actions

Image and font optimization

Project Structure

app/ - routing, pages, layouts

components/ - UI building blocks

public/ - static files

styles/ - global or module CSS

next.config.js - framework configuration

Building Workflow

Create routes inside `app/` directory

Use components inside server or client boundaries

Fetch data using server components or APIs

Style using CSS modules, Tailwind, or styled-components

Build and deploy via Vercel or Node servers

Difficulty Use Cases

Beginner: static pages

Intermediate: SSR pages + API routes

Advanced: RSC + streaming + middleware

Expert: multi-tenant full-stack SaaS

Community: open-source Next.js plugins

Comparisons

More full-stack than React alone

More enterprise-ready than SvelteKit

More flexible rendering than Angular

More SEO-friendly than Vue/Nuxt (historically)

Built for performance at scale

Versioning Timeline

2016 - Initial release

2019 - Major SSR/SSG improvements

2020 - Next.js 10 with image optimization

2022 - App Router + RSC (Next.js 13)

2023-2025 - Stabilized RSC, server actions, Turbopack

Glossary

RSC: React Server Components

ISR: Incremental Static Regeneration

Middleware: Edge-based request logic

Segment: A folder-based route unit

Layout: Persistent UI wrapper per route

Installation Setup

`npx create-next-app@latest my-app`

Enable TypeScript optionally during setup

Run dev server with `npm run dev`

Deploy instantly to Vercel

Use VSCode with Next.js + React plugins

Environment Setup

Install Node.js

Create Next.js app

Install VSCode + React plugins

Choose CSS framework

Connect to database if needed

Config Files

next.config.js - main config

package.json - scripts/deps

middleware.js - edge logic

app/layout.js - root layout

tailwind.config.js - if using Tailwind

Cli Commands

npx create-next-app - new project

npm run dev - start dev server

npm run build - production build

npm start - run build

npx next telemetry disable - disable telemetry

Internationalization

Built-in Next.js i18n routing

Middleware-based locale detection

Popular libraries like next-intl

Language-based dynamic routes

Localized metadata API

Accessibility

Semantic React components

ARIA support via React

Image optimization with alt text

Keyboard navigation support

Accessible routing with App Router

Ui Styling

CSS Modules

Tailwind CSS

Styled-components

Global styles in `app/globals.css`

Shadcn UI + Radix for components

State Management

React state & context

Zustand

Redux Toolkit

Jotai / Recoil

Server Actions for mutation state

Data Management

Fetch in Server Components

Use built-in caching

API routes for custom backend logic

Use SWR/React Query in client components

Connect Prisma/Drizzle to databases

Architecture

App Router-based architecture

Client + Server component model

Hybrid rendering strategy

File-based routing system

Middleware + Edge execution

Rendering Model

Server Components by default

Hybrid SSR/SSG/ISR/CSR

Streaming server rendering

Edge rendering via middleware

Automatic static optimization

Architectural Patterns

Server-first UI architecture

API routes for backend logic

Middleware for auth/rewrites

Layouts composition pattern

Component-based routing

Real World Architectures

Enterprise SaaS platforms

Ecommerce storefronts

Internal dashboards

AI inference apps

Multi-tenant multi-region systems

Design Principles

Performance-first

Server-first architecture

Minimal client JavaScript

Convention over configuration

End-to-end developer experience

Scalability Guide

Separate logic into server modules

Use caching for heavy data fetching

Split UI into server/client boundaries

Optimize bundling with Turbopack

Leverage Vercel’s global edge network

Migration Guide

Move from Pages Router -> App Router

Refactor components into server/client

Replace getServerSideProps with server components

Move _app/_document to layout.js

Use `route.js` for APIs instead of API folder

Performance Notes

Use Server Components to reduce bundle size

Prefer SSG/ISR where possible

Use `next/image` for optimized images

Cache fetch requests using built-in caching

Use edge functions for low-latency processing

Security Notes

Avoid exposing secrets in client components

Use API routes or server actions for secure logic

Sanitize user input

Enable Next.js security headers

Use middleware for auth & request filtering

Monitoring Analytics

Sentry for crash logging

Vercel Analytics

Web Vitals tracking

Log streaming via Vercel

Third-party tools like LogRocket

Code Quality

Use ESLint + Prettier

Follow React & Next best practices

Use TypeScript for safety

Write component tests

Monitor bundle size

Practical Examples

SEO-friendly blog with SSG

Ecommerce storefront with SSR

Real-time dashboard using server actions

Full-stack user auth system

ISR-powered marketing site

Troubleshooting

Check if component needs `use client`

Ensure correct rendering mode (SSR/SSG)

Fix data-fetching errors in server components

Verify route structure in the `app/` folder

Resolve hydration mismatches between server & client

Testing Guide

Unit test with Jest or Vitest

Component test with React Testing Library

E2E test with Playwright

Mock API routes in tests

Test RSC boundaries carefully

Deployment Options

Vercel (recommended)

Netlify

AWS / GCP / Azure

Docker containers

Edge deployment using middleware

Tools Ecosystem

Vercel platform & analytics

Next.js CLI

NextAuth.js for authentication

Prisma ORM for databases

Turbopack bundler (beta)

Integrations

Tailwind CSS

Prisma + PlanetScale / Supabase

tRPC

GraphQL (Apollo / URQL)

Firebase / Clerk / Auth0

Productivity Tips

Use Server Components for heavy logic

Use layouts for code reuse

Leverage built-in caching

Use Turbo tasks for faster builds

Integrate with Prisma for full-stack dev

Challenges

Build a dynamic blog using SSG

Create an authenticated dashboard

Implement server actions CRUD

Add middleware-based auth

Deploy a SaaS starter app

Learning Path

Learn React fundamentals

Understand App Router & routing

Master Server & Client Components

Learn Data Fetching & Rendering methods

Build a real full-stack app with API routes

Skill Improvement Plan

Week 1: React + Next.js basics

Week 2: Routing, layouts, client components

Week 3: SSR, SSG, ISR, caching

Week 4: API routes & databases

Week 5: Deployments, optimization & middleware

Interview Questions

Explain Server vs Client Components

How does ISR work in Next.js?

What is the App Router?

How does Next.js handle routing?

What are the benefits of RSC?

Cheat Sheet

`use client` - enables client component

`app/page.js` - root route

`app/layout.js` - shared layout

`[id]` - dynamic routes

`route.js` - API route handlers

Books

Learning Next.js

Fullstack Next.js

The Next.js Handbook

Mastering Next.js

React & Next.js Patterns

Tutorials

Vercel official tutorials

Next.js official course

Fireship crash course

Net Ninja Next.js tutorials

Frontend Masters Next.js course

Official Docs

https://nextjs.org/docs

https://nextjs.org/learn

Community Links

Next.js Discord

Reddit r/nextjs

Stack Overflow Next.js tag

GitHub Next.js repository

Vercel community forum

Community Support

Next.js Discord

Vercel community

Stack Overflow Next.js tag

GitHub issues & discussions

Reddit r/nextjs

Monetization

Build SaaS apps

Ecommerce stores

Next.js templates/themes

Agency services with Next.js

Internal enterprise portals

Future Roadmap

Better Turbopack stability

More RSC optimizations

Improved caching APIs

Simpler DX for server actions

Deeper AI integration via Vercel

When Not To Use

Simple static sites (use Astro instead)

Teams that dislike React

Apps with extremely custom routing needs

Lightweight widgets without routing

Beginner projects sensitive to complexity

Final Summary

Next.js is a top-tier full-stack React framework.

It offers hybrid SSR/SSG/ISR rendering.

The App Router enables scalable architectures using Server Components.

Ideal for SEO, dashboards, SaaS, and enterprise apps.

Backed by Vercel's ecosystem and rapid innovation.

Faq

Is Next.js full-stack?

Yes, with API routes, server components, and DB access.

Do I need React to learn Next.js?

Yes, it's built on React.

Does Next.js support TypeScript?

Yes, full support is built in.

Is Next.js good for SEO?

Yes, especially with SSR & SSG.

Is Next.js beginner-friendly?

Yes, although the App Router adds complexity.

Code Sample Descriptions

1

Next.js Counter with useState

import { useState } from 'react';

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

  return (
    <div className={isDark ? 'dark-theme' : 'light-theme'} style={{ padding: '2rem' }}>
      <h2>Counter: {count}</h2>
      <button onClick={() => setCount(count + 1)}>+</button>
      <button onClick={() => setCount(count - 1)}>-</button>
      <button onClick={() => setCount(0)}>Reset</button>
      <button onClick={() => setIsDark(!isDark)}>Switch Theme</button>
      <style jsx>{`
        .dark-theme { background: #222; color: #eee; min-height: 100vh; }
        .light-theme { background: #fff; color: #000; min-height: 100vh; }
        button { margin: 0 0.5rem; }
      `}</style>
    </div>
  );
}

Simple counter using useState with theme toggle in Next.js.

Let’s Try →
2

Next.js Counter with useEffect and localStorage

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    const savedCount = localStorage.getItem('count');
    const savedTheme = localStorage.getItem('isDark');
    if (savedCount) setCount(parseInt(savedCount, 10));
    if (savedTheme) setIsDark(savedTheme === 'true');
  }, []);

  useEffect(() => {
    localStorage.setItem('count', count);
    localStorage.setItem('isDark', isDark);
  }, [count, isDark]);

  return (
    <div className={isDark ? 'dark-theme' : 'light-theme'} style={{ padding: '2rem' }}>
      <h2>Counter: {count}</h2>
      <button onClick={() => setCount(count + 1)}>+</button>
      <button onClick={() => setCount(count - 1)}>-</button>
      <button onClick={() => setCount(0)}>Reset</button>
      <button onClick={() => setIsDark(!isDark)}>Switch Theme</button>
      <style jsx>{`
        .dark-theme { background: #222; color: #eee; min-height: 100vh; }
        .light-theme { background: #fff; color: #000; min-height: 100vh; }
        button { margin: 0 0.5rem; }
      `}</style>
    </div>
  );
}

Counter with useEffect and localStorage persistence in Next.js.

Let’s Try →
3

Next.js Counter using useReducer

import { useReducer } from 'react';

const initialState = { count: 0, isDark: false };
function reducer(state, action) {
  switch(action.type) {
    case 'INCREMENT': return { ...state, count: state.count + 1 };
    case 'DECREMENT': return { ...state, count: state.count - 1 };
    case 'RESET': return { ...state, count: 0 };
    case 'TOGGLE_THEME': return { ...state, isDark: !state.isDark };
    default: return state;
  }
}

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

  return (
    <div className={state.isDark ? 'dark-theme' : 'light-theme'} style={{ padding: '2rem' }}>
      <h2>Counter: {state.count}</h2>
      <button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
      <button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
      <button onClick={() => dispatch({ type: 'RESET' })}>Reset</button>
      <button onClick={() => dispatch({ type: 'TOGGLE_THEME' })}>Switch Theme</button>
      <style jsx>{`
        .dark-theme { background: #222; color: #eee; min-height: 100vh; }
        .light-theme { background: #fff; color: #000; min-height: 100vh; }
        button { margin: 0 0.5rem; }
      `}</style>
    </div>
  );
}

Uses useReducer for counter and theme state management.

Let’s Try →
4

Next.js Counter with Context

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

const CounterContext = createContext();
export function CounterProvider({ children }) {
  const [count, setCount] = useState(0);
  const [isDark, setIsDark] = useState(false);
  return (
    <CounterContext.Provider value={{ count, setCount, isDark, setIsDark }}>
      {children}
    </CounterContext.Provider>
  );
}

export default function Counter() {
  const { count, setCount, isDark, setIsDark } = useContext(CounterContext);
  return (
    <div className={isDark ? 'dark-theme' : 'light-theme'} style={{ padding: '2rem' }}>
      <h2>Counter: {count}</h2>
      <button onClick={() => setCount(count + 1)}>+</button>
      <button onClick={() => setCount(count - 1)}>-</button>
      <button onClick={() => setCount(0)}>Reset</button>
      <button onClick={() => setIsDark(!isDark)}>Switch Theme</button>
      <style jsx>{`
        .dark-theme { background: #222; color: #eee; min-height: 100vh; }
        .light-theme { background: #fff; color: #000; min-height: 100vh; }
        button { margin: 0 0.5rem; }
      `}</style>
    </div>
  );
}

Uses React Context to provide counter and theme globally.

Let’s Try →
5

Next.js Counter with TypeScript

import { useState } from 'react';

export default function Counter(): JSX.Element {
  const [count, setCount] = useState<number>(0);
  const [isDark, setIsDark] = useState<boolean>(false);

  return (
    <div className={isDark ? 'dark-theme' : 'light-theme'} style={{ padding: '2rem' }}>
      <h2>Counter: {count}</h2>
      <button onClick={() => setCount(count + 1)}>+</button>
      <button onClick={() => setCount(count - 1)}>-</button>
      <button onClick={() => setCount(0)}>Reset</button>
      <button onClick={() => setIsDark(!isDark)}>Switch Theme</button>
      <style jsx>{`
        .dark-theme { background: #222; color: #eee; min-height: 100vh; }
        .light-theme { background: #fff; color: #000; min-height: 100vh; }
        button { margin: 0 0.5rem; }
      `}</style>
    </div>
  );
}

Counter and theme toggle written in TypeScript for Next.js.

Let’s Try →
6

Next.js Counter with Inline Styles

import { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);
  const [isDark, setIsDark] = useState(false);
  const themeStyle = {
    background: isDark ? '#222' : '#fff',
    color: isDark ? '#eee' : '#000',
    minHeight: '100vh',
    padding: '2rem',
    textAlign: 'center'
  };

  return (
    <div style={themeStyle}>
      <h2>Counter: {count}</h2>
      <button onClick={() => setCount(count + 1)}>+</button>
      <button onClick={() => setCount(count - 1)}>-</button>
      <button onClick={() => setCount(0)}>Reset</button>
      <button onClick={() => setIsDark(!isDark)}>Switch Theme</button>
    </div>
  );
}

Uses inline styles for theme toggling instead of CSS classes.

Let’s Try →
7

Next.js Counter with Buttons Map

import { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);
  const [isDark, setIsDark] = useState(false);
  const buttons = [
    { label: '+', action: () => setCount(count + 1) },
    { label: '-', action: () => setCount(count - 1) },
    { label: 'Reset', action: () => setCount(0) }
  ];

  return (
    <div className={isDark ? 'dark-theme' : 'light-theme'} style={{ padding: '2rem', textAlign: 'center' }}>
      <h2>Counter: {count}</h2>
      {buttons.map((btn, idx) => <button key={idx} onClick={btn.action}>{btn.label}</button>)}
      <button onClick={() => setIsDark(!isDark)}>Switch Theme</button>
      <style jsx>{`
        .dark-theme { background: #222; color: #eee; min-height: 100vh; }
        .light-theme { background: #fff; color: #000; min-height: 100vh; }
        button { margin: 0 0.5rem; }
      `}</style>
    </div>
  );
}

Uses an array of button configs to render counter buttons dynamically.

Let’s Try →
8

Next.js Counter with useMemo

import { useState, useMemo } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);
  const [isDark, setIsDark] = useState(false);
  const double = useMemo(() => count * 2, [count]);

  return (
    <div className={isDark ? 'dark-theme' : 'light-theme'} style={{ padding: '2rem', textAlign: 'center' }}>
      <h2>Counter: {count} (Double: {double})</h2>
      <button onClick={() => setCount(count + 1)}>+</button>
      <button onClick={() => setCount(count - 1)}>-</button>
      <button onClick={() => setCount(0)}>Reset</button>
      <button onClick={() => setIsDark(!isDark)}>Switch Theme</button>
      <style jsx>{`
        .dark-theme { background: #222; color: #eee; min-height: 100vh; }
        .light-theme { background: #fff; color: #000; min-height: 100vh; }
        button { margin: 0 0.5rem; }
      `}</style>
    </div>
  );
}

Uses useMemo to compute double of count for demonstration.

Let’s Try →
9

Next.js Counter with Custom Hook

import { useState } from 'react';

function useCounter(initialCount = 0) {
  const [count, setCount] = useState(initialCount);
  const increment = () => setCount(c => c + 1);
  const decrement = () => setCount(c => c - 1);
  const reset = () => setCount(0);
  return { count, increment, decrement, reset };
}

export default function Counter() {
  const { count, increment, decrement, reset } = useCounter();
  const [isDark, setIsDark] = useState(false);

  return (
    <div className={isDark ? 'dark-theme' : 'light-theme'} style={{ padding: '2rem', textAlign: 'center' }}>
      <h2>Counter: {count}</h2>
      <button onClick={increment}>+</button>
      <button onClick={decrement}>-</button>
      <button onClick={reset}>Reset</button>
      <button onClick={() => setIsDark(!isDark)}>Switch Theme</button>
      <style jsx>{`
        .dark-theme { background: #222; color: #eee; min-height: 100vh; }
        .light-theme { background: #fff; color: #000; min-height: 100vh; }
        button { margin: 0 0.5rem; }
      `}</style>
    </div>
  );
}

Implements a custom useCounter hook for state management.

Let’s Try →

Frequently Asked Questions about Next-js

What is Next-js?

Next.js is a powerful React framework for building modern full-stack web applications with features like server-side rendering, static generation, routing, API endpoints, and server components. It emphasizes performance, scalability, and developer experience.

What are the primary use cases for Next-js?

SEO-optimized websites. Full-stack React apps with server routes. E-commerce storefronts. Dashboards and SaaS apps. Static or hybrid-rendered marketing sites

What are the strengths of Next-js?

Industry-leading SEO performance. Best-in-class developer experience. Full-stack capabilities in a single project. Highly scalable via Vercel’s edge network. Deep React ecosystem integration

What are the limitations of Next-js?

Learning curve due to multiple rendering strategies. Server Components may confuse beginners. Opinionated routing structure. Performance varies if misconfigured. Can feel heavy for small apps

How can I practice Next-js typing speed?

CodeSpeedTest offers 9+ real Next-js code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.