Skip to content

Common Snippets ​

One-liners and micro-patterns you probably don't need a package for.

Before using any snippet, ask if a community package already solves this better. These are documented for convenience and as a reference for your own implementations.

Table of Contents ​


Framework-Agnostic ​

cn() — clsx + tailwind-merge ​

Combine Tailwind classes with proper conflict resolution.

ts
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

Alternative: tailwind-merge and clsx are the community standard. This is just the canonical combination.


cleanedObject — Remove falsy values ​

Remove null, undefined, empty strings, and false from an object.

ts
import pickBy from "lodash/pickBy";

export const cleanedObject = <T extends object>(obj: T): Partial<T> =>
  pickBy(obj, (v) => v !== undefined && v !== null && v !== "" && v !== false);

Alternative: lodash.pickBy or inline with Object.fromEntries(Object.entries(obj).filter(...)).


localStorage with TTL ​

Store values with automatic expiry.

ts
type StorageValue<T> = {
  value: T;
  expiry: number;
};

export const setWithExpiry = <T>(key: string, value: T, ttlMs: number): void => {
  const item: StorageValue<T> = {
    value,
    expiry: Date.now() + ttlMs,
  };
  localStorage.setItem(key, JSON.stringify(item));
};

export const getWithExpiry = <T>(key: string): T | null => {
  const itemStr = localStorage.getItem(key);
  if (!itemStr) return null;

  const item: StorageValue<T> = JSON.parse(itemStr);
  if (Date.now() > item.expiry) {
    localStorage.removeItem(key);
    return null;
  }

  return item.value;
};

Alternative: store2, lscache, idb-keyval for more robust storage.


isDistinct — Array uniqueness check ​

Check if all elements in an array are unique.

ts
export const isDistinct = <T>(arr: T[]): boolean => new Set(arr).size === arr.length;

Alternative: This is a one-liner — just inline it where needed.


getDomainAndTLD — URL domain extractor ​

Extract domain.tld from a full URL.

ts
export const getDomainAndTLD = (url: string): string | null => {
  try {
    const { hostname } = new URL(url);
    const parts = hostname.split(".");
    if (parts.length < 2) return hostname;
    return `${parts.at(-2)}.${parts.at(-1)}`;
  } catch {
    return null;
  }
};

Alternative: psl (Public Suffix List) for proper TLD handling including co.uk, com.au, etc.


detectFileTypeFromUrl ​

Detect if a URL points to an image or document based on extension.

ts
export const detectFileTypeFromUrl = (url: string): "image" | "document" | "unknown" => {
  const imageExtensions = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg"];
  const documentExtensions = [".pdf", ".doc", ".docx", ".xls", ".xlsx"];
  const ext = url.split("?")[0].toLowerCase();

  if (imageExtensions.some((e) => ext.endsWith(e))) return "image";
  if (documentExtensions.some((e) => ext.endsWith(e))) return "document";
  return "unknown";
};

Alternative: mime or mime-types for comprehensive MIME type detection.


copyToClipboard ​

ts
export const copyToClipboard = async (text: string): Promise<void> => {
  await navigator.clipboard.writeText(text);
};

Alternative: clipboard-copy for broader browser support and fallback handling.


downloadBlobFile ​

Trigger a browser download from a Blob.

ts
export const downloadBlobFile = (blob: Blob, filename: string): void => {
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url);
};

Alternative: file-saver for cross-browser compatibility and large file handling.


validatePassword — Basic strength check ​

ts
export const validatePassword = (password: string): boolean => {
  const hasUpper = /[A-Z]/.test(password);
  const hasLower = /[a-z]/.test(password);
  const hasNumber = /[0-9]/.test(password);
  const hasSpecial = /[^A-Za-z0-9]/.test(password);
  const hasMinLength = password.length >= 8;

  return hasUpper && hasLower && hasNumber && hasSpecial && hasMinLength;
};

Alternative: password-validator for configurable rules. zxcvbn for actual strength scoring (dictionary attacks, common passwords, etc.).


React Hooks ​

useIsomorphicLayoutEffect ​

Use useLayoutEffect on the client, useEffect on the server.

ts
import { useEffect, useLayoutEffect } from "react";

export const useIsomorphicLayoutEffect =
  typeof window !== "undefined" ? useLayoutEffect : useEffect;

Alternative: use-isomorphic-layout-effect on npm.


useMediaQuery ​

Subscribe to CSS media queries.

ts
import { useSyncExternalStore } from "react";

export function useMediaQuery(query: string): boolean {
  return useSyncExternalStore(
    (callback) => {
      const match = window.matchMedia(query);
      match.addEventListener("change", callback);
      return () => match.removeEventListener("change", callback);
    },
    () => window.matchMedia(query).matches,
    () => false, // Server fallback
  );
}

Alternative: react-responsive, @react-hook/media-query, usehooks-ts.


useReducedMotion ​

Detect if the user prefers reduced motion.

ts
export function useReducedMotion(): boolean {
  return useMediaQuery("(prefers-reduced-motion: reduce)");
}

Alternative: framer-motion exports useReducedMotion(). usehooks-ts has it too.


useScrollToTop ​

Scroll to top on route change.

ts
import { useEffect } from "react";
import { useLocation } from "react-router"; // or @tanstack/react-router

export const useScrollToTop = () => {
  const { pathname } = useLocation();

  useEffect(() => {
    window.scrollTo({ top: 0, behavior: "smooth" });
  }, [pathname]);
};

Alternative: react-router has ScrollRestoration component. Inline in your root layout.


Testing Utilities ​

createStoreResettable ​

Reset a Zustand store to its initial state between tests.

ts
import { type StoreApi } from "zustand";

type ResettableStore<T> = {
  reset: () => void;
  setState: (state: Partial<T>) => void;
  getState: () => T;
};

export function createStoreResettable<T extends object>(store: StoreApi<T>): ResettableStore<T> {
  const initialState = store.getState();

  return {
    reset: () => store.setState(initialState, true),
    setState: (state) => store.setState(state, false),
    getState: () => store.getState(),
  };
}

Usage:

ts
const resettableStore = createStoreResettable(useAuthStore);

beforeEach(() => {
  resettableStore.reset();
});

createLocalStorageMock ​

Mock localStorage for tests involving Zustand persist middleware.

ts
export function createLocalStorageMock(): Storage {
  const store: Record<string, string> = {};

  return {
    get length() {
      return Object.keys(store).length;
    },
    getItem: (key) => store[key] ?? null,
    setItem: (key, value) => {
      store[key] = value;
    },
    removeItem: (key) => {
      delete store[key];
    },
    clear: () => {
      for (const key of Object.keys(store)) {
        delete store[key];
      }
    },
    key: (index) => Object.keys(store)[index] ?? null,
  };
}

Usage:

ts
const localStorageMock = createLocalStorageMock();
Object.defineProperty(window, "localStorage", {
  value: localStorageMock,
  writable: true,
});

Alternative: Vitest's vi.stubGlobal('localStorage', mock).


When to Use These ​

These snippets are for when:

  1. You don't want to add a dependency for a 5-line function
  2. You need to adapt the behavior slightly (e.g., different falsy-value handling in cleanedObject)
  3. You're building a quick prototype and will refactor later

When NOT to use these:

  1. The community package has edge cases you haven't considered (e.g., psl handles co.uk correctly, your regex doesn't)
  2. The community package is actively maintained and will get bug fixes you won't think to apply
  3. You're copy-pasting the same snippet into 3+ projects — then it might be worth extracting to an internal shared module

See Also ​