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 2, 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 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;
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;
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;
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;
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];
};
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;
};
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;
};
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;
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
// });
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 useWindowSize hook allows you to dynamically track the window size within your React components. This can be useful for building responsive UIs or adjusting layout based on the viewport dimensions.
import { useState, useEffect } from 'react';
const useWindowSize = () => {
const [size, setSize] = useState({
width: window.innerWidth,
height: window.innerHeight
});
useEffect(() => {
const handleResize = () => {
setSize({
width: window.innerWidth,
height: window.innerHeight
});
};
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return size;
};
// Usage
// const { width, height } = useWindowSize();
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');
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.
Enjoy Coding :)
Advertisement
Advertisement
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.
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.
Anuj Sharma
Last Updated Oct 28, 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 Aug 3, 2025
Explore the implementation of setTimeout in JavaScript with a detailed explanation for every step. Understand all scenarios expected to implement the setTimeout polyfill.
Anuj Sharma
Last Updated Oct 26, 2025
In this post, we will going to cover the step-by-step implementation of Infinite Currying Sum with a code example. This is one of the most common JavaScript Interview questions.
Anuj Sharma
Last Updated Oct 26, 2025
Understand the step-by-step implementation of Infinite Currying Multiplication in JavaScript with a code example.
Subscribe to FrontendGeek Hub for the frontend interview preparation, interview experiences, curated resources and roadmaps.
© 2024 FrontendGeek. All rights reserved