Skip to main content

Shorts

Quick code snippets and tips for everyday development.

useDebounce Hook

A simple React hook for debouncing values. Useful for search inputs and API calls.

import { useState, useEffect } from "react";
 
export function useDebounce<T>(value: T, delay: number = 500): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value);
 
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);
 
    return () => clearTimeout(timer);
  }, [value, delay]);
 
  return debouncedValue;
}
 
// Usage
const [search, setSearch] = useState("");
const debouncedSearch = useDebounce(search, 300);
 
useEffect(() => {
  // Only fires 300ms after user stops typing
  fetchResults(debouncedSearch);
}, [debouncedSearch]);
reacthookstypescript

Branded Types in TypeScript

Prevent mixing up primitive types that represent different things using branded types.

// Create a branded type utility
type Brand<T, B extends string> = T & { __brand: B };
 
// Define branded types
type UserId = Brand<string, "UserId">;
type PostId = Brand<string, "PostId">;
 
// Constructor functions
const UserId = (id: string) => id as UserId;
const PostId = (id: string) => id as PostId;
 
// Now TypeScript prevents mixing them up
function getUser(id: UserId) { /* ... */ }
function getPost(id: PostId) { /* ... */ }
 
const userId = UserId("user_123");
const postId = PostId("post_456");
 
getUser(userId); // OK
getUser(postId); // Type error! Can't pass PostId as UserId
typescript

Gradient Text with Tailwind CSS

Create beautiful gradient text effects using only Tailwind CSS utility classes.

<!-- Basic gradient text -->
<h1 class="bg-gradient-to-r from-blue-400 via-purple-500 to-pink-500
           bg-clip-text text-transparent">
  Gradient Heading
</h1>
 
<!-- Animated gradient (add to your CSS) -->
<h1 class="animate-gradient bg-[length:200%_auto]
           bg-gradient-to-r from-blue-400 via-purple-500 to-blue-400
           bg-clip-text text-transparent">
  Animated Gradient
</h1>
/* Add this animation to your global CSS or Tailwind config */
@keyframes gradient {
  0% { background-position: 0% center; }
  100% { background-position: 200% center; }
}
 
.animate-gradient {
  animation: gradient 3s linear infinite;
}
csstailwind