Explore the Most Common Custom Hooks in React asked in the React Interviews. It includes the code example of all the custom hooks in react for a quick revision before interview.
Anuj Sharma
Last Updated Nov 27, 2025

Custom hooks improve the overall reusability in the react application and reduce down the boilerplate code. Understanding custom hooks are so important that Nowadays Custom Hooks in React are one of the most asked React Interviews questions.
Any number of custom hooks can be make as per the requirement, so to help you out we have captured the 20 most asked Custom Hooks in React with code implementation for quick revision before your frontend interview
The useFetch hook in react is used for making HTTP requests in React components, and handle the loading, error states better.
import { useState, useEffect } from 'react';
const useFetch = (url) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
const response = await fetch(url);
const result = await response.json();
setData(result);
setLoading(false);
};
fetchData();
}, [url]);
return { data, loading };
};
export default useFetch;
Detailed useFetch Hook Guide →
The useToggle hook is used to toggle between two states.
import { useState } from 'react';
const useToggle = (initialState = false) => {
const [state, setState] = useState(initialState);
const toggle = () => {
setState(!state);
};
return [state, toggle];
};
export default useToggle;
Detailed useToggle Hook Guide →
The useTheme hook is used for managing themes in a React application.
import { useState } from 'react';
const useTheme = () => {
const [theme, setTheme] = useState('light');
const toggleTheme = () => {
setTheme(theme === 'light' ? 'dark' : 'light');
};
return [theme, toggleTheme];
};
export default useTheme;
Detailed useTheme Hook Guide →
The usePrefersColorScheme hook is used to detect the user's preferred color scheme.
import { useState, useEffect } from 'react';
const usePrefersColorScheme = () => {
const [colorScheme, setColorScheme] = useState('light');
useEffect(() => {
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
setColorScheme(mediaQuery.matches ? 'dark' : 'light');
}, []);
return colorScheme;
};
export default usePrefersColorScheme;
The useLocalStorage hook is used to persist state in local storage.
import { useState } from 'react';
const useLocalStorage = (key, initialValue) => {
const [value, setValue] = useState(() => {
const storedValue = localStorage.getItem(key);
return storedValue ? JSON.parse(storedValue) : initialValue;
});
const setStoredValue = (newValue) => {
setValue(newValue);
localStorage.setItem(key, JSON.stringify(newValue));
};
return [value, setStoredValue];
};
export default useLocalStorage;
Detailed useLocalStorage Hook Guide →
The useSessionStorage hook is similar to useLocalStorage but interacts with session storage instead.
// Implementation of useSessionStorage
const useSessionStorage = (key, initialValue) => {
const [storedValue, setStoredValue] = useState(() => {
const item = window.sessionStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
});
const setValue = value => {
setStoredValue(value);
window.sessionStorage.setItem(key, JSON.stringify(value));
};
return [storedValue, setValue];
};
Detailed useSessionStorage Hook Guide →
The useDebounce hook delays the execution of a function until a specified time has elapsed since the last invocation.
// Implementation of useDebounce
const useDebounce = (value, delay) => {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
};
Detailed useDebounce Hook Guide →
The useThrottle hook limits the rate at which a function is executed.
// Implementation of useThrottle
const useThrottle = (value, delay) => {
const [throttledValue, setThrottledValue] = useState(value);
const lastExecTime = useRef(0);
useEffect(() => {
const now = Date.now();
if (now - lastExecTime.current > delay) {
setThrottledValue(value);
lastExecTime.current = now;
}
}, [value, delay]);
return throttledValue;
};
Detailed useThrottle Hook Guide →
Custom hook to observe when an element enters or exits the viewport.
import { useEffect, useRef, useState } from 'react';
const useIntersectionObserver = (target, options) => {
const [isVisible, setIsVisible] = useState(false);
const observer = useRef(new IntersectionObserver(
([entry]) => setIsVisible(entry.isIntersecting),
options
));
useEffect(() => {
observer.current.observe(target);
return () => observer.current.disconnect();
}, [target]);
return isVisible;
};
export default useIntersectionObserver;
Custom hook to store the previous value of a state variable.
import { useEffect, useRef } from 'react';
const usePrevious = (value) => {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
};
export default usePrevious;
Detailed usePrevious Hook Guide →
The useOnClickOutside hook is used to detect clicks that occur outside a specified element. This is commonly used for implementing dropdowns, modals, or any component that needs to close when a user clicks outside of it.
import { useEffect } from 'react';
const 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]);
};
// Usage
// const ref = useRef();
// useOnClickOutside(ref, () => {
// // Close the dropdown or modal
// });
Detailed useOnClickOutside Hook Guide →
The useCopyToClipboard hook is used for copying text to the clipboard. It provides a convenient way to implement copy functionality in your React components.
const useCopyToClipboard = () => {
const copyToClipboard = (text) => {
navigator.clipboard.writeText(text)
.then(() => {
console.log('Text copied to clipboard');
})
.catch((error) => {
console.error('Failed to copy text to clipboard:', error);
});
};
return { copyToClipboard };
};
// Usage
// const { copyToClipboard } = useCopyToClipboard();
// copyToClipboard('Text to be copied');
The useInfiniteScroll hook allows you to handle the large list where data is populated (locally or from server using API call) dynamically while user scrolls and hit the bottom of the page (or Intersection point).
IntersectionObserver API can be used to implement this custom hook and This react hook can be useful for building application involving large amount of data to showcase in a lazy loaded fashion. Example - Catalog page of an e-commerce application.
const useInfiniteScroll = (callback) => {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
callback();
}
});
useEffect(() => {
observer.observe(document.getElementById('infinite-scroll-trigger'));
return () => {
observer.disconnect();
};
}, []);
};
Detailed useInfiniteScroll Hook Guide →
The useDocumentTitle hook allows you to dynamically set the document title based on the state of your component. This can be useful for updating the title of your web application based on the content being displayed.
import { useEffect } from 'react';
const useDocumentTitle = (title) => {
useEffect(() => {
document.title = title;
}, [title]);
};
// Usage
// useDocumentTitle('Page Title');
Detailed useDocumentTitle Hook Guide →
useClipboard allows you to copy text to the clipboard and optionally track whether the copy succeeded (for example, to show a “Copied!” toast or tooltip).
import { useState } from "react";
function useClipboard(timeout = 2000) {
const [copied, setCopied] = useState(false);
const copy = async (text) => {
if (!text) return;
try {
await navigator.clipboard.writeText(text);
setCopied(true);
setTimeout(() => setCopied(false), timeout);
} catch (error) {
console.error("Failed to copy: ", error);
setCopied(false);
}
};
return { copied, copy };
}
The useOnlineStatus custom hook is used to track the online status of the user's browser. This can be useful for showing a message when the user is offline or for handling network-related features.
import { useState, useEffect } from 'react';
const useOnlineStatus = () => {
const [isOnline, setIsOnline] = useState(navigator.onLine);
useEffect(() => {
const handleOnline = () => setIsOnline(true);
const handleOffline = () => setIsOnline(false);
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
return () => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, []);
return isOnline;
};
export default useOnlineStatus;
The useScrollPosition custom hook is used to track the scroll position of the page. This can be handy for implementing effects based on scroll position, such as sticky headers or lazy loading content.
import { useState, useEffect } from 'react';
const useScrollPosition = () => {
const [scrollPosition, setScrollPosition] = useState(window.scrollY);
useEffect(() => {
const handleScroll = () => {
setScrollPosition(window.scrollY);
};
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
return scrollPosition;
};
export default useScrollPosition;
The useKeyPress custom hook is used to detect when a specific key is pressed. This can be used for implementing keyboard shortcuts or handling user input based on key presses.
import { useState, useEffect } from 'react';
const useKeyPress = (targetKey) => {
const [keyPressed, setKeyPressed] = useState(false);
const downHandler = ({ key }) => {
if (key === targetKey) {
setKeyPressed(true);
}
};
const upHandler = ({ key }) => {
if (key === targetKey) {
setKeyPressed(false);
}
};
useEffect(() => {
window.addEventListener('keydown', downHandler);
window.addEventListener('keyup', upHandler);
return () => {
window.removeEventListener('keydown', downHandler);
window.removeEventListener('keyup', upHandler);
};
}, [targetKey]);
return keyPressed;
};
export default useKeyPress;
The useMediaQuery custom hook is used to track the match of a CSS media query. This can be useful for implementing responsive designs and adapting components based on screen size or device type.
import { useState, useEffect } from 'react';
const useMediaQuery = (query) => {
const [matches, setMatches] = useState(false);
useEffect(() => {
const mediaQuery = window.matchMedia(query);
setMatches(mediaQuery.matches);
const handler = (event) => setMatches(event.matches);
mediaQuery.addListener(handler);
return () => {
mediaQuery.removeListener(handler);
};
}, [query]);
return matches;
};
export default useMediaQuery;
useWindowSize lets you reactively track the browser window dimensions, useful for responsive UIs, conditionally rendering layouts, or adapting components based on screen size.
import { useState, useEffect } from "react";
function useWindowSize() {
const [windowSize, setWindowSize] = useState({
width: window.innerWidth,
height: window.innerHeight,
});
useEffect(() => {
function handleResize() {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
}
// Add event listener
window.addEventListener("resize", handleResize);
// Call handler immediately so state is up to date
handleResize();
// Clean up listener on unmount
return () => window.removeEventListener("resize", handleResize);
}, []);
return windowSize;
}
Thats It !!
Thanks for going through all of these custom hooks in react, these hooks cover all most patterns to implement the custom hooks. Even if there is any other custom hook implementation comes in the interview you will be able to implement any new custom hooks based on the knowledge of the above 20 custom hooks in react.
Happy Coding :)
Anuj Sharma
A seasoned Sr. Engineering Manager at GoDaddy (Ex-Dell) with over 12+ years of experience in the frontend technologies. A frontend tech enthusiast passionate building SaaS application to solve problem. Know more about me 🚀
Be the first to share your thoughts!
No comments yet.
Start the conversation!
Build Your Portfolio
Help the Community
Strengthen Your Skills
Share your knowledge by writing a blog or quick notes. Your contribution can help thousands of frontend developers ace their interviews and grow their careers! 🚀
Anuj Sharma
Last Updated Nov 23, 2025
Explore code explanation of useToggle() custom hook in react to handle the toggle event efficiently.
Anuj Sharma
Last Updated Nov 24, 2025
Understand step by step how to flatten nested array in javascript using recursion, also explore the flatten of complex array of object.
Anuj Sharma
Last Updated Nov 23, 2025
Find the step-by-step explanation of the useFetch custom hook in React that helps in fetching the data from an API and handling loading, error states.
Anuj Sharma
Last Updated Nov 23, 2025
Implement useThrottle Custom Hook In React (Interview) to limit the number of APi calls to improve the performance of application.
Anuj Sharma
Last Updated Oct 2, 2025
Explore Polyfill for map, filter and reduce array methods in JavaScript. A detailed explanation of Map, filter and reduce polyfills in JS helps you to know the internal working of these array methods.
Alok Kumar Giri
Last Updated Jun 2, 2025
Code snippet examples which will help to grasp the concept of Hoisting in JavaScript, with solutions to understand how it works behind the scene.
Subscribe to FrontendGeek Hub for frontend interview preparation, interview experiences, curated resources and roadmaps.
© 2025 FrontendGeek. All rights reserved