Explore snippets
Discover reusable code snippets, examples, fixes, and ideas shared by developers, students, and teams.
URLSearchParams Filter State
Read, update, and remove page filters without manually concatenating query strings.
function updateFilters(changes) {
const url = new URL(window.location.href);
Object.entries(changes).forEach(([key, value]) => {
const normalizedValue = String(value ?? '').trim();
if (normalizedValue === '') {
url.searchParams.delete(key);
Next.js Route Error Boundary
Handle uncaught route segment errors and let the user retry without a full reload.
// app/dashboard/error.tsx
'use client';
import { useEffect } from 'react';
type ErrorPageProps = {
error: Error & {
digest?: string;
};
reset: () => void;
};
export default function DashboardError({
error,
reset,
}: ErrorPageProps) {
Next.js Server Action Form with useActionState
Connect a Next.js Server Action to a client form with validation and pending state.
// app/actions.ts
'use server';
export type CreateUserState = {
message: string;
errors: {
email?: string;
};
};
export async function createUser(
previousState: CreateUserState,
formData: FormData,
): Promise<CreateUserState> {
React Error Boundary Component
Catch rendering errors in a subtree and provide a retryable fallback UI.
import {
Component,
type ErrorInfo,
type ReactNode,
} from 'react';
type Props = {
children: ReactNode;
fallback?: ReactNode;
};
type State = {
hasError: boolean;
};
export class ErrorBoundary extends Component<Props, State> {
state: State = {
Typed Context Reducer Pattern
Combine React context and useReducer with typed actions and a safe custom hook.
'use client';
import {
createContext,
type ReactNode,
useContext,
useReducer,
} from 'react';
type CartState = {
itemCount: number;
};
type CartAction =
| { type: 'add'; quantity: number }
| { type: 'clear' };
Online Status with useSyncExternalStore
Subscribe to the browser online state through React useSyncExternalStore.
'use client';
import { useSyncExternalStore } from 'react';
function subscribe(callback: () => void) {
window.addEventListener('online', callback);
window.addEventListener('offline', callback);
return () => {
Reusable useDebouncedValue Hook
Delay a rapidly changing value before triggering searches, validation, or API requests.
'use client';
import { useEffect, useState } from 'react';
export function useDebouncedValue<T>(
value: T,
delay = 300,
): T {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
Lazy Component Loading with Suspense
Load a large component only when it is rendered and show a fallback during download.
'use client';
import { lazy, Suspense, useState } from 'react';
const AnalyticsChart = lazy(
() => import('./analytics-chart'),
);
export function AnalyticsPanel() {
const [isOpen, setIsOpen] = useState(false);
return (
<section>
<button
Accessible Form Fields with useId
Generate stable IDs for reusable form controls and accessible help text.
import { useId } from 'react';
type TextFieldProps = {
label: string;
name: string;
helpText?: string;
};
export function TextField({
label,
name,
helpText,
}: TextFieldProps) {
const inputId = useId();
const helpId = `${inputId}-help`;
Non-Blocking Tabs with useTransition
Switch expensive tab content without blocking urgent UI updates.
'use client';
import { useState, useTransition } from 'react';
const tabs = ['overview', 'activity', 'settings'] as const;
type Tab = (typeof tabs)[number];
export function DashboardTabs() {
const [activeTab, setActiveTab] = useState<Tab>('overview');
Deferred Search Results with useDeferredValue
Keep a search input responsive while a larger result list updates at lower priority.
'use client';
import { useDeferredValue, useMemo, useState } from 'react';
type Product = {
id: number;
name: string;
};
export function ProductSearch({ products }: { products: Product[] }) {
const [query, setQuery] = useState('');
Optimistic Todo List with useOptimistic
Show a new todo immediately while the asynchronous save operation completes in the background.
'use client';
import { startTransition, useOptimistic, useState } from 'react';
type Todo = {
id: string;
text: string;
pending?: boolean;
};
type Props = {
initialTodos: Todo[];
createTodo: (text: string) => Promise<Todo>;
};
React Form Validation with useActionState
Manage form validation, submission status, and server-style action results with React useActionState.
'use client';
import { useActionState } from 'react';
type FormState = {
message: string;
errors: {
email?: string;
};
};
const initialState: FormState = {
message: '',
errors: {},
};
async function subscribe(
previousState: FormState,