Examples of Useful Custom Hooks
0 650
๐ง What Are Custom Hooks?
Custom Hooks are reusable functions in React that encapsulate hook logic (like useState, 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 between true 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 in localStorage 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