Code Snippets

Ready-to-use code snippets for common patterns and solutions in modern web development.

React: Custom Hook for Local Storage

A reusable hook to sync state with localStorage

react
hookslocalStoragestate
TSX
1400">import { useState, useEffect } 400">from 'react';
2 
3400">function useLocalStorage<T>(key: 400">string, initialValue: T) {
4 400">const [storedValue, setStoredValue] = useState<T>(() => {
5 400">try {
6 400">const item = window.localStorage.300">getItem(key);
7 400">return item ? JSON.300">parse(item) : initialValue;
8 } 400">catch (error) {
9 console.300">error(error);
10 400">return initialValue;
11 }
12 });
13 
14 400">const setValue = (value: T | ((val: T) => T)) => {
15 400">try {
16 400">const valueToStore = value 400">instanceof Function ? 300">value(storedValue) : value;
17 300">setStoredValue(valueToStore);
18 window.localStorage.300">setItem(key, JSON.300">stringify(valueToStore));
19 } 400">catch (error) {
20 console.300">error(error);
21 }
22 };
23 
24 400">return [storedValue, setValue] 400">as 400">const;
25}
26 
27// Usage
28400">const [theme, setTheme] = 300">useLocalStorage('theme', 'light');

Next.js: API Route with Error Handling

Robust API route with validation and error handling

nextjs
apivalidationerror-handling
TypeScript
1400">import { NextApiRequest, NextApiResponse } 400">from 'next';
2400">import { z } 400">from 'zod';
3 
4400">const schema = z.400">object({
5 email: z.400">string().300">email(),
6 name: z.400">string().300">min(2),
7});
8 
9400">export 400">default 400">async 400">function 300">handler(
10 req: NextApiRequest,
11 res: NextApiResponse
12) {
13 400">if (req.method !== 'POST') {
14 400">return res.300">status(405).300">json({ message: 'Method not allowed' });
15 }
16 
17 400">try {
18 400">const validatedData = schema.300">parse(req.body);
19
20 // Process data...
21 400">const result = 400">await 300">processData(validatedData);
22
23 400">return res.300">status(200).300">json({ success: 400">true, data: result });
24 } 400">catch (error) {
25 400">if (error 400">instanceof z.ZodError) {
26 400">return res.300">status(400).300">json({
27 success: 400">false,
28 errors: error.errors.300">map(e => ({
29 path: e.path.300">join('.'),
30 message: e.message
31 }))
32 });
33 }
34
35 console.300">error('API Error:', error);
36 400">return res.300">status(500).300">json({
37 success: 400">false,
38 message: 'Internal server error'
39 });
40 }
41}

TypeScript: Utility Type for Partial Deep

Create a deep partial type for nested objects

typescript
typesutilitydeep-partial
TypeScript
1type DeepPartial<T> = T 400">extends 400">object ? {
2 [P in keyof T]?: DeepPartial<T[P]>;
3} : T;
4 
5// Usage
6interface User {
7 id: 400">number;
8 profile: {
9 name: 400">string;
10 address: {
11 street: 400">string;
12 city: 400">string;
13 };
14 };
15}
16 
17400">const partialUser: DeepPartial<User> = {
18 profile: {
19 address: {
20 city: "New York"
21 }
22 }
23};

Tailwind CSS: Responsive Card Component

A fully responsive card with dark mode support

tailwindcss
uiresponsivedark-mode
TSX
1400">function 300">Card({ title, description, icon }: CardProps) {
2 400">return (
3 <div className="
4 bg-white dark:bg-slate-800
5 rounded-xl
6 border border-slate-200 dark:border-slate-700
7 p-6
8 shadow-sm hover:shadow-md
9 transition-all duration-200
10 ">
11 <div className="flex items-start gap-4">
12 <div className="
13 p-3
14 rounded-lg
15 bg-blue-100 dark:bg-blue-900/30
16 text-blue-600 dark:text-blue-400
17 ">
18 {icon}
19 </div>
20 <div className="flex-1">
21 <h3 className="
22 text-lg font-semibold
23 text-slate-900 dark:text-white
24 mb-2
25 ">
26 {title}
27 </h3>
28 <p className="
29 text-slate-600 dark:text-slate-400
30 leading-relaxed
31 ">
32 {description}
33 </p>
34 </div>
35 </div>
36 </div>
37 );
38}

Zod: Schema with Conditional Validation

Advanced schema with conditional fields based on other values

zod
validationschemaconditional
TypeScript
1400">import { z } 400">from 'zod';
2 
3400">const userSchema = z.400">object({
4 role: z.300">enum(['user', 'admin', 'moderator']),
5 email: z.400">string().300">email(),
6 permissions: z.300">array(z.400">string()).300">optional(),
7})
8.300">refine(
9 (data) => {
10 400">if (data.role === 'admin' && (!data.permissions || data.permissions.length === 0)) {
11 400">return 400">false;
12 }
13 400">return 400">true;
14 },
15 {
16 message: 'Admins must have at least one permission',
17 path: ['permissions']
18 }
19)
20.300">transform((data) => ({
21 ...data,
22 createdAt: 400">new 400">Date().300">toISOString(),
23 isActive: 400">true
24}));
25 
26// Usage
27400">const validated = userSchema.300">parse({
28 role: 'admin',
29 email: 'admin@example.com',
30 permissions: ['read', 'write']
31});

React Query: Infinite Scroll Pagination

Implement infinite scroll with TanStack Query

tanstack-query
paginationinfinite-scrolldata-fetching
TSX
1400">import { useInfiniteQuery } 400">from '@tanstack/react-query';
2 
3400">function 300">useInfinitePosts() {
4 400">return 300">useInfiniteQuery({
5 queryKey: ['posts'],
6 queryFn: 400">async ({ pageParam = 1 }) => {
7 400">const response = 400">await 300">fetch(`/api/posts?page=${pageParam}`);
8 400">return response.300">json();
9 },
10 getNextPageParam: (lastPage, allPages) => {
11 400">if (lastPage.hasNextPage) {
12 400">return allPages.length + 1;
13 }
14 400">return 400">undefined;
15 },
16 initialPageParam: 1,
17 });
18}
19 
20400">function 300">PostsList() {
21 400">const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = 300">useInfinitePosts();
22
23 300">useEffect(() => {
24 400">const handleScroll = () => {
25 400">if (
26 window.innerHeight + window.scrollY >= document.body.offsetHeight - 500 &&
27 hasNextPage &&
28 !isFetchingNextPage
29 ) {
30 300">fetchNextPage();
31 }
32 };
33
34 window.300">addEventListener('scroll', handleScroll);
35 400">return () => window.300">removeEventListener('scroll', handleScroll);
36 }, [hasNextPage, isFetchingNextPage, fetchNextPage]);
37
38 400">return (
39 <div>
40 {data?.pages.300">map((page, pageIndex) => (
41 <div key={pageIndex}>
42 {page.posts.300">map((post) => (
43 <PostCard key={post.id} post={post} />
44 ))}
45 </div>
46 ))}
47 {isFetchingNextPage && <LoadingSpinner />}
48 </div>
49 );
50}

Filter by Technology

Submit Your Snippet

Have a useful code snippet? Share it with the community.