Code Snippets
Useful, battle-tested code snippets for common programming tasks. Copy, customize, and use in your projects to save time and avoid reinventing the wheel.
Code Snippets
Categories
Languages
Production Ready
Debounced Search Function
intermediatePrevent excessive API calls by debouncing user input for search functionality.
Usage:
Perfect for search inputs, auto-complete, and any user input that triggers API calls.
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
// Usage example
const searchHandler = debounce((query) => {
console.log('Searching for:', query);
// Make API call here
}, 300);
// Use with input field
document.getElementById('search').addEventListener('input', (e) => {
searchHandler(e.target.value);
});
CSS Gradient Button
beginnerBeautiful animated gradient button with hover effects and accessibility features.
Usage:
Use for primary action buttons, CTAs, and important interactive elements.
.gradient-button {
background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
border: none;
color: white;
padding: 12px 24px;
border-radius: 8px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
position: relative;
overflow: hidden;
}
.gradient-button:hover {
transform: translateY(-2px);
box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
}
.gradient-button:focus {
outline: 3px solid rgba(102, 126, 234, 0.5);
outline-offset: 2px;
}
.gradient-button:active {
transform: translateY(0);
}
React Custom Hook - useLocalStorage
intermediateSync React state with localStorage automatically with this custom hook.
Usage:
Perfect for persisting user preferences, form data, and app state across sessions.
import { useState, useEffect } from 'react';
function useLocalStorage(key, initialValue) {
// Get value from localStorage or use initial value
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error('Error reading localStorage:', error);
return initialValue;
}
});
// Update localStorage when state changes
const setValue = (value) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.error('Error setting localStorage:', error);
}
};
return [storedValue, setValue];
}
// Usage example
function MyComponent() {
const [name, setName] = useLocalStorage('name', '');
return (
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter your name"
/>
);
}
Array Utility Functions
beginnerHandy utility functions for common array operations and transformations.
Usage:
Essential utilities for data manipulation, filtering, and array transformations.
// Remove duplicates from array
const unique = (arr) => [...new Set(arr)];
// Group array items by property
const groupBy = (arr, key) => {
return arr.reduce((groups, item) => {
const group = item[key];
groups[group] = groups[group] || [];
groups[group].push(item);
return groups;
}, {});
};
// Chunk array into smaller arrays
const chunk = (arr, size) => {
return Array.from({ length: Math.ceil(arr.length / size) }, (_, i) =>
arr.slice(i * size, i * size + size)
);
};
// Find intersection of two arrays
const intersection = (arr1, arr2) => {
return arr1.filter(item => arr2.includes(item));
};
// Usage examples
const numbers = [1, 2, 2, 3, 4, 4, 5];
console.log(unique(numbers)); // [1, 2, 3, 4, 5]
const users = [
{ name: 'John', role: 'admin' },
{ name: 'Jane', role: 'user' },
{ name: 'Bob', role: 'admin' }
];
console.log(groupBy(users, 'role'));
console.log(chunk([1, 2, 3, 4, 5, 6], 2)); // [[1, 2], [3, 4], [5, 6]]
Loading Spinner Component
beginnerReusable React loading spinner with customizable size and color.
Usage:
Show loading states during API calls, page transitions, or any async operations.
import React from 'react';
const LoadingSpinner = ({
size = 'md',
color = 'primary',
className = ''
}) => {
const sizeClasses = {
sm: 'w-4 h-4',
md: 'w-8 h-8',
lg: 'w-12 h-12',
xl: 'w-16 h-16'
};
const colorClasses = {
primary: 'text-blue-600',
secondary: 'text-gray-600',
success: 'text-green-600',
warning: 'text-yellow-600',
error: 'text-red-600'
};
return (
<div className={`flex items-center justify-center ${className}`}>
<svg
className={`animate-spin ${sizeClasses[size]} ${colorClasses[color]}`}
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
/>
</svg>
</div>
);
};
// Usage example
function App() {
const [loading, setLoading] = useState(true);
return (
<div>
{loading ? (
<LoadingSpinner size="lg" color="primary" />
) : (
<div>Content loaded!</div>
)}
</div>
);
}
Responsive Grid Layout
intermediateCSS Grid layout that adapts to different screen sizes automatically.
Usage:
Perfect for card layouts, product grids, image galleries, and responsive content.
.auto-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 1.5rem;
padding: 1rem;
}
/* For smaller minimum widths on mobile */
@media (max-width: 768px) {
.auto-grid {
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1rem;
}
}
/* Grid items */
.grid-item {
background: white;
border-radius: 8px;
padding: 1.5rem;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
transition: transform 0.2s ease;
}
.grid-item:hover {
transform: translateY(-2px);
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}
API Error Handler
advancedRobust error handling utility for API calls with retry logic and user-friendly messages.
Usage:
Use for all API calls to ensure consistent error handling and user experience.
class APIError extends Error {
constructor(message, status, data) {
super(message);
this.name = 'APIError';
this.status = status;
this.data = data;
}
}
async function apiCall(url, options = {}, retries = 3) {
const defaultOptions = {
headers: {
'Content-Type': 'application/json',
},
...options,
};
for (let attempt = 1; attempt <= retries; attempt++) {
try {
const response = await fetch(url, defaultOptions);
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new APIError(
errorData.message || `HTTP ${response.status}: ${response.statusText}`,
response.status,
errorData
);
}
return await response.json();
} catch (error) {
if (attempt === retries || error instanceof APIError) {
throw error;
}
// Wait before retrying (exponential backoff)
await new Promise(resolve =>
setTimeout(resolve, Math.pow(2, attempt) * 1000)
);
}
}
}
// Usage example
async function fetchUserData(userId) {
try {
const userData = await apiCall(`/api/users/${userId}`);
return userData;
} catch (error) {
if (error instanceof APIError) {
console.error('API Error:', error.message, error.status);
// Handle specific error cases
if (error.status === 404) {
throw new Error('User not found');
}
} else {
console.error('Network Error:', error.message);
throw new Error('Unable to connect to server');
}
}
}
Form Validation Hook
advancedReact hook for form validation with custom rules and real-time feedback.
Usage:
Perfect for complex forms that need real-time validation and user feedback.
import { useState, useEffect } from 'react';
function useFormValidation(initialValues, validationRules) {
const [values, setValues] = useState(initialValues);
const [errors, setErrors] = useState({});
const [touched, setTouched] = useState({});
const validateField = (name, value) => {
const rules = validationRules[name];
if (!rules) return '';
for (const rule of rules) {
const error = rule(value, values);
if (error) return error;
}
return '';
};
const handleChange = (name, value) => {
setValues(prev => ({ ...prev, [name]: value }));
if (touched[name]) {
const error = validateField(name, value);
setErrors(prev => ({ ...prev, [name]: error }));
}
};
const handleBlur = (name) => {
setTouched(prev => ({ ...prev, [name]: true }));
const error = validateField(name, values[name]);
setErrors(prev => ({ ...prev, [name]: error }));
};
const validateAll = () => {
const newErrors = {};
let isValid = true;
Object.keys(validationRules).forEach(name => {
const error = validateField(name, values[name]);
newErrors[name] = error;
if (error) isValid = false;
});
setErrors(newErrors);
setTouched(Object.keys(validationRules).reduce((acc, key) => {
acc[key] = true;
return acc;
}, {}));
return isValid;
};
return {
values,
errors,
touched,
handleChange,
handleBlur,
validateAll,
isValid: Object.values(errors).every(error => !error)
};
}
// Validation rules
const required = (value) => !value ? 'This field is required' : '';
const email = (value) =>
!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value) ? 'Invalid email address' : '';
const minLength = (min) => (value) =>
value.length < min ? `Must be at least ${min} characters` : '';
// Usage example
function LoginForm() {
const {
values,
errors,
touched,
handleChange,
handleBlur,
validateAll,
isValid
} = useFormValidation(
{ email: '', password: '' },
{
email: [required, email],
password: [required, minLength(6)]
}
);
const handleSubmit = (e) => {
e.preventDefault();
if (validateAll()) {
console.log('Form submitted:', values);
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={values.email}
onChange={(e) => handleChange('email', e.target.value)}
onBlur={() => handleBlur('email')}
placeholder="Email"
/>
{touched.email && errors.email && <div className="error">{errors.email}</div>}
<input
type="password"
value={values.password}
onChange={(e) => handleChange('password', e.target.value)}
onBlur={() => handleBlur('password')}
placeholder="Password"
/>
{touched.password && errors.password && <div className="error">{errors.password}</div>}
<button type="submit" disabled={!isValid}>
Login
</button>
</form>
);
}
Contribute a Snippet
Have a useful code snippet that could help other developers? Share it with our community and help others build faster.