Code Explainers

Javascript code explainers

javascript
import { useState, useCallback, useEffect } from 'react';
 
function usePaginatedProducts(pageSize = 20) {
  const [items, setItems] = useState([]);

Cursor-based infinite scroll with a React hook

custom-hooks pagination async-fetching
Intermediate 8 steps
javascript
import { useCallback, useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';
 
const FOCUSABLE = 'a[href], button:not([disabled]), textarea, input, select, [tabindex]:not([tabindex="-1"])';

Building an accessible modal in React

focus-trap accessibility portals
Advanced 9 steps
javascript
'use client';
 
import { useOptimistic, useTransition } from 'react';
import { toggleLike } from '@/app/actions/likes';

Optimistic like buttons in Next.js

optimistic-ui react-hooks server-actions
Intermediate 7 steps
javascript
const express = require('express');
const router = express.Router();
 
router.get('/articles/:slug', async (req, res, next) => {

Content negotiation with res.format in Express

content-negotiation routing error-handling
Intermediate 9 steps
javascript
function makeTableSorter(rows) {
  const state = { key: null, dir: 1 };
 
  const compareBy = (key) => (a, b) => {

Building a stateful table sorter in JavaScript

closures stable-sort comparators
Intermediate 7 steps
javascript
function createAutocomplete(input, resultsList, { minChars = 2, delay = 300 } = {}) {
  let timer = null;
  let controller = null;
 

Building a debounced autocomplete widget

debouncing abortcontroller closures
Intermediate 9 steps
javascript
import Link from "next/link";
import { prisma } from "@/lib/prisma";
 
const PAGE_SIZE = 20;

A searchable, paginated table as a Next.js Server Component

server-components pagination search
Intermediate 6 steps
javascript
import { Suspense } from 'react';
import { getProducts } from '@/lib/api/products';
import { formatPrice } from '@/lib/format';
 

Streaming a product list with Suspense in Next.js

server-components suspense streaming
Intermediate 8 steps
javascript
const DEFAULT_OPTIONS = {
  method: 'GET',
  timeout: 5000,
  retries: 3,

A resilient fetch wrapper with retries and timeout

fetch retry timeout
Intermediate 8 steps
javascript
import { parsePhoneNumberFromString } from 'libphonenumber-js';
 
export class PhoneValidationError extends Error {
  constructor(message, code) {

Normalizing phone numbers with typed errors

validation error-handling custom-errors
Intermediate 6 steps
javascript
const express = require('express');
const { z } = require('zod');
const router = express.Router();
 

Validating query params with Zod in Express

validation schema-parsing query-building
Intermediate 9 steps
javascript
const RESERVED_SLUGS = new Set(['new', 'edit', 'admin', 'api']);
 
function slugify(title) {
  return title

Generating URL-safe unique slugs

string-normalization regex deduplication
Intermediate 9 steps
javascript
class EventEmitter {
  constructor() {
    this.listeners = new Map();
  }

Building an EventEmitter in JavaScript

pub-sub closures map
Intermediate 7 steps
javascript
const express = require('express');
const compression = require('compression');
const zlib = require('zlib');
 

Tuning Express response compression

compression middleware http
Intermediate 9 steps
javascript
import { NextResponse } from 'next/server'
 
const UPSTREAM = 'https://api.exchangerate.host/latest'
 

A cached exchange-rate proxy in Next.js

route-handler caching revalidation
Intermediate 7 steps
javascript
const logger = require('./logger');
 
class AppError extends Error {
  constructor(message, statusCode = 500, details = null) {

Centralized error handling in Express

error-handling middleware custom-errors
Intermediate 8 steps
javascript
const formatters = new Map();
 
function getFormatter(locale, currency) {
  const key = `${locale}:${currency}`;

Caching Intl.NumberFormat for currency formatting

memoization internationalization caching
Intermediate 8 steps
javascript
class DOMBatcher {
  constructor() {
    this.reads = [];
    this.writes = [];

Batching DOM reads and writes to avoid layout thrash

batching requestanimationframe layout-thrashing
Intermediate 8 steps