Code Explainers

Javascript code explainers

javascript
'use server'
 
import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'

How a Next.js Server Action updates a post

server-actions authorization validation
Intermediate 7 steps
javascript
const express = require('express');
 
const v1 = express.Router();
 

Versioning an API with Express Routers

api versioning routing modularity
Intermediate 10 steps
javascript
const RATE_LIMIT = 100;
const WINDOW_MS = 60 * 1000;
const BLOCK_MS = 5 * 60 * 1000;
 

Building a rate-limiting middleware in Express

rate-limiting middleware closures
Intermediate 9 steps
javascript
const transitions = {
  cart: { checkout: 'shipping' },
  shipping: { submitAddress: 'payment', back: 'cart' },
  payment: { submitPayment: 'review', back: 'shipping' },

A finite state machine for checkout flow

state-machine event-driven data-driven-design
Intermediate 7 steps
javascript
import { useState, useEffect, useCallback, useRef } from "react";
 
export function usePersistentForm(storageKey, initialValues) {
  const [values, setValues] = useState(() => {

A React hook that persists form state to localStorage

custom-hooks localstorage debounce
Intermediate 9 steps
javascript
function groupBy(items, keySelector) {
  const resolveKey = typeof keySelector === 'function'
    ? keySelector
    : (item) => item[keySelector];

Building a flexible groupBy in JavaScript

higher-order-functions reduce data-transformation
Intermediate 6 steps
javascript
function makeReorderableList(listEl, onReorder) {
  let draggedItem = null;
 
  listEl.addEventListener('dragstart', (e) => {

Drag-to-reorder lists with the HTML5 drag API

drag-and-drop event-delegation dom-manipulation
Intermediate 8 steps
javascript
import Papa from 'papaparse';
 
const MAX_SIZE = 5 * 1024 * 1024;
 

Validating and parsing CSV uploads in the browser

promises csv-parsing validation
Intermediate 8 steps
javascript
async function fetchAllPages(baseUrl, { pageSize = 100, headers = {} } = {}) {
  const results = [];
  let cursor = null;
 

Cursor-based pagination with fetch

pagination async-await fetch
Intermediate 6 steps
javascript
import { useCallback, useEffect, useRef, useState } from 'react';
 
export function useInfiniteScroll(fetchPage) {
  const [items, setItems] = useState([]);

Building an infinite scroll hook in React

custom-hooks intersection-observer pagination
Advanced 6 steps
javascript
import { useState, useEffect, useMemo } from 'react';
 
function useDebounce(value, delay = 300) {
  const [debounced, setDebounced] = useState(value);

Debounced search with cancellation in React

custom-hooks debounce abortcontroller
Intermediate 9 steps
javascript
import { useState, useEffect } from "react";
 
export function useUser(userId) {
  const [user, setUser] = useState(null);

How a data-fetching hook works in React

custom-hooks data-fetching abortcontroller
Intermediate 8 steps
javascript
import { useMemo, useState } from 'react';
 
function ProductList({ products }) {
  const [query, setQuery] = useState('');

Memoizing a filtered list in React

memoization derived-state filtering
Intermediate 8 steps
javascript
function initLazyLoad(root = document) {
  const images = root.querySelectorAll('img[data-src]');
 
  if (!('IntersectionObserver' in window)) {

How lazy image loading works

lazy-loading intersectionobserver progressive-enhancement
Intermediate 8 steps
javascript
import { notFound } from 'next/navigation';
 
const PER_PAGE = 24;
const SORT_OPTIONS = ['relevance', 'price-asc', 'price-desc', 'newest'];

Parsing search params in a Next.js page

input-validation query-params pagination
Intermediate 10 steps
javascript
import { NextResponse } from 'next/server';
import Stripe from 'stripe';
import { headers } from 'next/headers';
 

Handling Stripe webhooks in Next.js

webhooks signature verification payment processing
Intermediate 7 steps
javascript
const fs = require('fs');
const path = require('path');
 
router.get('/downloads/:name', (req, res, next) => {

Streaming file downloads in Express

streaming backpressure file-download
Advanced 9 steps
javascript
async function pollJobUntilComplete(jobId, { interval = 2000, timeout = 60000, signal } = {}) {
  const deadline = Date.now() + timeout;
 
  while (true) {

Polling a job until it finishes in JavaScript

polling async-await abortsignal
Intermediate 6 steps