Code Snippets

A searchable library of useful code snippets, utilities, and solutions to common problems. Copy, paste, and adapt for your projects.

Debounce Hook

React hook for debouncing values to optimize performance on rapid changes.

#react#hooks#performance
typescript
import { useEffect, useState } from 'react'

export function useDebounce<T>(value: T, delay: number = 300): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value)

  useEffect(() => {
    const timer = setTimeout(() => setDebouncedValue(value), delay)
    return () => clearTimeout(timer)
  }, [value, delay])

  return debouncedValue
}

Fetch with Timeout

Wrapper for fetch API with configurable timeout to prevent hanging requests.

#fetch#async#utilities
typescript
export async function fetchWithTimeout(
  url: string,
  options: RequestInit = {},
  timeout: number = 8000
): Promise<Response> {
  const controller = new AbortController()
  const timeoutId = setTimeout(() => controller.abort(), timeout)

  try {
    const response = await fetch(url, {
      ...options,
      signal: controller.signal,
    })
    clearTimeout(timeoutId)
    return response
  } catch (error) {
    clearTimeout(timeoutId)
    throw error
  }
}

Generate Embeddings Batch

Efficiently generate OpenAI embeddings in batches to avoid rate limits.

#openai#embeddings#ai
typescript
import OpenAI from 'openai'

const openai = new OpenAI()

export async function generateEmbeddingsBatch(
  texts: string[],
  batchSize: number = 100
): Promise<number[][]> {
  const embeddings: number[][] = []

  for (let i = 0; i < texts.length; i += batchSize) {
    const batch = texts.slice(i, i + batchSize)
    const response = await openai.embeddings.create({
      model: 'text-embedding-ada-002',
      input: batch,
    })
    embeddings.push(...response.data.map(d => d.embedding))

    // Delay to avoid rate limits
    if (i + batchSize < texts.length) {
      await new Promise(resolve => setTimeout(resolve, 1000))
    }
  }

  return embeddings
}

Tailwind Container Query

Use CSS container queries with Tailwind for component-based responsive design.

#tailwind#css#responsive
typescript
/* Add to tailwind.config.ts */
module.exports = {
  plugins: [
    require('@tailwindcss/container-queries'),
  ],
}

/* Usage in components */
<div className="@container">
  <div className="@sm:grid-cols-2 @lg:grid-cols-3 grid">
    {/* Content */}
  </div>
</div>

Let's Create Something Amazing Together

Whether you have a project in mind or just want to chat, I'm always open to discussing new opportunities and ideas.