Examples of Useful Custom Hooks
0 716
🔧 What Are Custom Hooks?
Custom Hooks are reusable functions in React that encapsulate hook logic (likeuseState, useEffect, useRef, etc.) into modular, maintainable, and shareable code. They help you follow the DRY (Don't Repeat Yourself) principle by abstracting repetitive logic. 🚀
✨ 1. useToggle – Toggle Boolean State
This hook toggles betweentrue and false. Great for modals, dropdowns, or switch states.
import { useState } from 'react';
function useToggle(initial = false) {
const [state, setState] = useState(initial);
const toggle = () => setState(prev => !prev);
return [state, toggle];
}
const [isOpen, toggleModal] = useToggle();
â±ï¸ 2. useTimeout – Delay Execution
Executes a callback after a specified timeout.
import { useEffect, useRef } from 'react';
function useTimeout(callback, delay) {
const savedCallback = useRef();
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
if (delay === null) return;
const id = setTimeout(() => savedCallback.current(), delay);
return () => clearTimeout(id);
}, [delay]);
}
📱 3. useMediaQuery – Detect Screen Size
Responsive behavior in JavaScript:
import { useState, useEffect } from 'react';
function useMediaQuery(query) {
const [matches, setMatches] = useState(() => window.matchMedia(query).matches);
useEffect(() => {
const media = window.matchMedia(query);
const listener = () => setMatches(media.matches);
media.addEventListener('change', listener);
return () => media.removeEventListener('change', listener);
}, [query]);
return matches;
}
const isMobile = useMediaQuery("(max-width: 768px)");
ðŸ•µï¸ 4. useOnClickOutside – Detect Outside Click
Closes dropdowns or modals when clicking outside an element.
import { useEffect } from 'react';
function useOnClickOutside(ref, handler) {
useEffect(() => {
const listener = (event) => {
if (!ref.current || ref.current.contains(event.target)) return;
handler(event);
};
document.addEventListener("mousedown", listener);
return () => {
document.removeEventListener("mousedown", listener);
};
}, [ref, handler]);
}
📦 5. useLocalStorage – Persist State
Save data inlocalStorage and sync with state:
import { useState } from 'react';
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch {
return initialValue;
}
});
const setValue = (value) => {
setStoredValue(value);
window.localStorage.setItem(key, JSON.stringify(value));
};
return [storedValue, setValue];
}
const [name, setName] = useLocalStorage('username', 'Guest');
🔠6. usePrevious – Get Previous Value
Track a value from the previous render:
import { useEffect, useRef } from 'react';
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}
const prevCount = usePrevious(count);
🧪 7. useDebounce – Delay Value Updates
Ideal for search fields and input-heavy components:
import { useState, useEffect } from 'react';
function useDebounce(value, delay) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const handler = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(handler);
}, [value, delay]);
return debounced;
}
const debouncedSearch = useDebounce(searchTerm, 300);
📡 8. useFetch – Abstract API Calls
Simplify and reuse API request logic:
import { useEffect, useState } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
let isMounted = true;
fetch(url)
.then((res) => res.json())
.then((data) => isMounted && setData(data))
.catch(setError)
.finally(() => isMounted && setLoading(false));
return () => (isMounted = false);
}, [url]);
return { data, loading, error };
}
📋 Summary
- ✅
useToggle– Boolean switch - ✅
useTimeout– Delayed effect - ✅
useMediaQuery– Responsive layouts - ✅
useOnClickOutside– Detect user interaction - ✅
useLocalStorage– Persist data - ✅
usePrevious– Track previous values - ✅
useDebounce– Optimize user input - ✅
useFetch– Simplify data loading
🚀 Final Thoughts
Custom hooks aren’t just a luxury — they’re a necessity in modern React development. With the right custom hooks in your toolkit, you can reduce code duplication, boost readability, and accelerate development like a pro! 💪⚛ï¸If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:




Comments
Waiting for your comments