Explore 10 custom React hooks that are most commonly asked in frontend interviews.
![10 Frequently Asked Custom React Hooks for Interviews [Part 2]](https://dqy38fnwh4fqs.cloudfront.net/UHP69ODABQAJGDDFMBDN76GLRNNP/blog/featured-c5261f3b-b305-4329-8667-129e78a71145.webp)
Mastering custom hooks is essential for any senior-level frontend interview. These hooks further improve reusability across your application and significantly reduce boilerplate code.
Below are the final 10 frequently asked custom React hooks, including their code implementations and detailed guides from FrontendGeek.
The useTheme hook is used for managing themes (such as light and dark modes) throughout a React application.
import { useState, useEffect } from 'react';
const useTheme = () => {
const [theme, setTheme] = useState('light');
const toggleTheme = () => setTheme((prev) => (prev === 'light' ? 'dark' : 'light'));
return { theme, toggleTheme };
};
📌 Detailed Explanation - Custom useTheme Hook
This hook is used to detect the user's preferred color scheme based on their system settings.
import { useState, useEffect } from 'react';
const usePrefersColorScheme = () => {
const [isDarkMode, setIsDarkMode] = useState(
window.matchMedia('(prefers-color-scheme: dark)').matches
);
useEffect(() => {
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handler = (e) => setIsDarkMode(e.matches);
mediaQuery.addEventListener('change', handler);
return () => mediaQuery.removeEventListener('change', handler);
}, []);
return isDarkMode ? 'dark' : 'light';
};
Similar to useLocalStorage, this hook interacts with session storage to persist state for the duration of the page session.
import { useState, useEffect } from 'react';
const useSessionStorage = (key, initialValue) => {
const [value, setValue] = useState(() => {
const saved = sessionStorage.getItem(key);
return saved ? JSON.parse(saved) : initialValue;
});
useEffect(() => {
sessionStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
};
📌 Detailed Explanation - Custom useSessionStorage Hook
The useDocumentTitle hook allows you to dynamically set the document title based on the state of your component.
import { useEffect } from 'react';
const useDocumentTitle = (title) => {
useEffect(() => {
document.title = title;
}, [title]);
};
📌 Detailed Explanation - Custom useDocumentTitle Hook
This custom hook allows you to fetch data from an API at regular intervals, centralizing the polling logic.
import { useEffect } from 'react';
const usePolling = (callback, interval) => {
useEffect(() => {
const id = setInterval(callback, interval);
return () => clearInterval(id); // Cleanup ensures no memory leaks
}, [callback, interval]);
};
📌 Detailed Explanation - Custom usePolling Hook
The useOnlineStatus hook is used to track the online status of the user's browser, enabling features like offline notifications.
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;
};
📌 Detailed Explanation - Custom useOnlineStatus Hook
This custom hook is used to track the scroll position of the page, which is useful for sticky headers or triggering scroll-based effects.
import { useState, useEffect } from 'react';
const useScrollPosition = () => {
const [scrollPos, setScrollPos] = useState(0);
useEffect(() => {
const handleScroll = () => setScrollPos(window.scrollY);
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
return scrollPos;
};
📌 Detailed Explanation - Custom useScrollPosition Hook
The useKeyPress hook detects when a specific key is pressed, helping implement keyboard shortcuts or custom user input handling.
import { useState, useEffect } from 'react';
const useKeyPress = (targetKey) => {
const [keyPressed, setKeyPressed] = useState(false);
useEffect(() => {
const downHandler = ({ key }) => { if (key === targetKey) setKeyPressed(true); };
const upHandler = ({ key }) => { if (key === targetKey) setKeyPressed(false); };
window.addEventListener('keydown', downHandler);
window.addEventListener('keyup', upHandler);
return () => {
window.removeEventListener('keydown', downHandler);
window.removeEventListener('keyup', upHandler);
};
}, [targetKey]);
return keyPressed;
};
📌 Detailed Explanation - Custom useKeyPress Hook
This hook tracks the match of a CSS media query, allowing you to adapt components based on screen size or device type.
import { useState, useEffect } from 'react';
const 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;
};
📌 Detailed Explanation - Custom useMediaQuery Hook
The useWindowSize hook lets you reactively track browser window dimensions, which is useful for building responsive UIs or conditionally rendering layouts.
import { useState, useEffect } from 'react';
const useWindowSize = () => {
const [windowSize, setWindowSize] = useState({
width: window.innerWidth,
height: window.innerHeight,
});
useEffect(() => {
const handleResize = () => setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return windowSize;
};
📌 Detailed Explanation - Custom useWindowSize Hook
That's the end of this blog,
Don't forget to check Part 1 to prepare for all the important Custom Hooks for the interview
Happy Coding :))
0
0
0