10 Useful React Snippets I Reuse in Almost Every Project
When working on React projects, I often find myself writing the same small pieces of code again and again.
Here are 10 simple React snippets that can save time in everyday development.
1. useDebounce
Useful when working with search inputs, filters, or API requests.
import { useEffect, useState } from "react";
function useDebounce(value, delay = 500) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const timer = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debouncedValue;
}
This prevents an API request from running on every keystroke.
2. useLocalStorage
A simple way to persist state in the browser.
import { useEffect, useState } from "react";
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : initialValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
This can be useful for preferences, themes, filters, and other client-side settings.
3. usePrevious
Sometimes you need to know what a value was before the latest render.
import { useEffect, useRef } from "react";
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}
4. useClickOutside
Useful for dropdowns, modals, menus, and popups.
import { useEffect } from "react";
function useClickOutside(ref, callback) {
useEffect(() => {
function handleClick(event) {
if (ref.current && !ref.current.contains(event.target)) {
callback();
}
}
document.addEventListener("mousedown", handleClick);
return () => {
document.removeEventListener("mousedown", handleClick);
};
}, [ref, callback]);
}
5. useMediaQuery
Useful when a component needs to respond to screen size.
import { useEffect, useState } from "react";
function useMediaQuery(query) {
const [matches, setMatches] = useState(false);
useEffect(() => {
const media = window.matchMedia(query);
const update = () => setMatches(media.matches);
update();
media.addEventListener("change", update);
return () => media.removeEventListener("change", update);
}, [query]);
return matches;
}
Example:
const isMobile = useMediaQuery("(max-width: 768px)");
6. useToggle
A small hook for boolean state.
import { useState } from "react";
function useToggle(initialValue = false) {
const [value, setValue] = useState(initialValue);
const toggle = () => setValue((current) => !current);
return [value, toggle];
}
Perfect for menus, modals, accordions, and visibility states.
7. Copy to Clipboard
You don't always need a library for copying text.
async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
return false;
}
}
Example:
await copyToClipboard("Hello React!");
8. Format API Errors
Keeping API errors consistent makes frontend code easier to maintain.
function getErrorMessage(error) {
if (error instanceof Error) {
return error.message;
}
return "Something went wrong";
}
Then:
try {
await fetchData();
} catch (error) {
console.error(getErrorMessage(error));
}
9. Generate a Unique ID
For simple client-side use cases:
function generateId() {
return `${Date.now()}-${Math.random().toString(36).slice(2)}`;
}
For security-sensitive identifiers, use a cryptographically secure approach instead.
10. Conditional Class Names
For small projects, a simple helper can be enough:
function cn(...classes) {
return classes.filter(Boolean).join(" ");
}
Example:
const className = cn(
"button",
isActive && "button-active",
disabled && "button-disabled"
);
Final Thoughts
These snippets are small, but having reusable patterns ready can save a surprising amount of development time.
Iām building a collection of reusable React, Next.js, JavaScript, Tailwind CSS, and Regex snippets at SnippetCrafted.
If you have a React snippet you use constantly, share it in the comments. I'd love to see what other developers are reusing in their projects.
Top comments (0)