hooks

typescript
export interface UploadHandle {
  promise: Promise<{ status: number; body: string }>;
  xhr: XMLHttpRequest;
}

export function uploadFile(

React File Upload with Live Progress Bar Using XMLHttpRequest

react file-upload xmlhttprequest
by codesnips 3 tabs
typescript
export type EventMap = Record<string, unknown[]>;

type Listener<Args extends unknown[]> = (...args: Args) => void;

export class TypedEmitter<Events extends EventMap> {
  private listeners = new Map<keyof Events, Set<Listener<any>>>();

Type-Safe Event Emitter With Strongly-Typed Listener Payloads in TypeScript

typescript events event-emitter
by codesnips 3 tabs
typescript
import { useCallback, useEffect, useRef, useState } from 'react';

export type CopyStatus = 'idle' | 'copied' | 'error';

function fallbackCopy(text: string): boolean {
  const textarea = document.createElement('textarea');

Frontend: copy-to-clipboard with fallback

frontend ux react
by codesnips 3 tabs
typescript
import { Response } from 'express';

type Client = { id: number; res: Response };

const clients = new Map<string, Set<Client>>();
let nextId = 1;

SSE endpoint for server-to-browser events

realtime sse express
by codesnips 3 tabs
typescript
import React, { useMemo } from 'react';
import { VirtualList } from './VirtualList';

interface LogEntry {
  id: number;
  level: 'info' | 'warn' | 'error';

Virtualized List in React: Render Only Visible Rows on Scroll

react virtualization windowing
by codesnips 3 tabs
javascript
import { useCallback, useEffect, useState } from 'react';

function parseSearch(search) {
  const params = new URLSearchParams(search);
  const out = {};
  for (const [key, value] of params.entries()) out[key] = value;

Sync React Form State to the URL Query String with a Debounced useSearchParams Hook

react hooks url-state
by codesnips 3 tabs
javascript
import { useCallback, useEffect, useRef, useState } from 'react';

export function usePaginatedFetch(fetchPage, { pageSize = 20 } = {}) {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

Infinite Scroll in React with IntersectionObserver and a Paginated Fetch Hook

react hooks infinite-scroll
by codesnips 3 tabs
typescript
import { useMemo } from "react";

export type SortDir = "asc" | "desc";
export interface SortConfig<T> {
  key: keyof T;
  dir: SortDir;

Memoized Async Search With a Cached Selector Hook in React

react hooks usememo
by codesnips 3 tabs
javascript
import { useEffect, useState } from "react";

export function useDebouncedValue(value, delay = 300) {
  const [debounced, setDebounced] = useState(value);

  useEffect(() => {

Debounced Search Input in React with a Reusable useDebouncedValue Hook

react hooks debounce
by codesnips 3 tabs
javascript
export const initialCart = { items: {} };

export function cartReducer(state, action) {
  switch (action.type) {
    case 'ADD_ITEM': {
      const { product, qty = 1 } = action;

Persist and Hydrate a Shopping Cart with useReducer and localStorage

react hooks usereducer
by codesnips 3 tabs
javascript
import { createContext, useContext, useEffect, useMemo, useState } from 'react';
import { fetchCurrentUser, postLogin, postLogout } from './api';

const AuthContext = createContext(null);

export function AuthProvider({ children }) {

Protecting React Routes with an Auth Context and a RequireAuth Wrapper

react react-router authentication
by codesnips 4 tabs
javascript
const BASE_URL = "/api/search";

export async function searchProducts(query, { signal } = {}) {
  const params = new URLSearchParams({ q: query, limit: "10" });
  const res = await fetch(`${BASE_URL}?${params}`, {
    signal,

Cancel Stale Autocomplete Requests with AbortController in a React Hook

react hooks abortcontroller
by codesnips 3 tabs