Explore 10 custom React hooks that are most commonly asked in frontend interviews.
![10 Frequently Asked Custom React Hooks for Interviews [Part 1]](https://dqy38fnwh4fqs.cloudfront.net/UHP69ODABQAJGDDFMBDN76GLRNNP/blog/featured-8b0e7ee0-d4a3-4198-b25b-6ece6f017bf5.webp)
Below are the code implementations for the 10 frequently asked custom React hooks discussed in our previous conversation.
These implementations are based on the logical patterns and requirements described in the sources, such as using useState for state management, useEffect for side effects and cleanup, and the IntersectionObserver API for viewport tracking.
Used for making HTTP requests and managing loading and error states.
import { useState, useEffect } from 'react';
const useFetch = (url) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
const result = await response.json();
setData(result);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading, error };
};
📌 Detailed Explanation - Detailed useFetch Hook Guide
A utility for switching between two states (e.g., boolean values).
import { useState } from 'react';
const useToggle = (initialValue = false) => {
const [value, setValue] = useState(initialValue);
const toggle = () => setValue((prev) => !prev);
return [value, toggle];
};
📌 Detailed Explanation - Detailed useToggle Hook Guide
Persists state in the browser's local storage across page refreshes.
import { useState, useEffect } from 'react';
const useLocalStorage = (key, initialValue) => {
const [value, setValue] = useState(() => {
const saved = localStorage.getItem(key);
return saved ? JSON.parse(saved) : initialValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
};
📌 Detailed Explanation - Detailed useLocalStorage Hook Guide
Delays function execution until a specified time has elapsed since the last call.
import { useState, useEffect } from 'react';
const useDebounce = (value, delay) => {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => clearTimeout(handler); // Cleanup function from source
}, [value, delay]);
return debouncedValue;
};
📌 Detailed Explanation - Detailed useDebounce Hook Guide
Limits the execution rate of a function to once per specified interval.
import { useState, useEffect, useRef } from 'react';
const useThrottle = (value, limit) => {
const [throttledValue, setThrottledValue] = useState(value);
const lastRan = useRef(Date.now());
useEffect(() => {
const handler = setTimeout(() => {
if (Date.now() - lastRan.current >= limit) {
setThrottledValue(value);
lastRan.current = Date.now();
}
}, limit - (Date.now() - lastRan.current));
return () => clearTimeout(handler);
}, [value, limit]);
return throttledValue;
};
📌 Detailed Explanation - Detailed useThrottle Hook Guide
Observes when an element enters or exits the viewport using the IntersectionObserver API.
import { useState, useEffect, useRef } from 'react';
const useIntersectionObserver = (options) => {
const [isIntersecting, setIsIntersecting] = useState(false);
const targetRef = useRef(null);
useEffect(() => {
const observer = new IntersectionObserver(([entry]) => {
setIsIntersecting(entry.isIntersecting);
}, options);
if (targetRef.current) observer.observe(targetRef.current);
return () => observer.disconnect();
}, [options]);
return [targetRef, isIntersecting];
};
📌 Detailed Explanation - Detailed useIntersectionObserver Hook Guide
Stores and accesses the previous value of a state or prop from the last render.
import { useEffect, useRef } from 'react';
const usePrevious = (value) => {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
};
📌 Detailed Explanation - Detailed usePrevious Hook Guide
Detects clicks outside a specific element to close components like modals.
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]);
};
📌 Detailed Explanation - Detailed useOnClickOutside Hook Guide
Manages the interaction with the system clipboard.
import { useState } from 'react';
const useCopyToClipboard = () => {
const [copiedText, setCopiedText] = useState(null);
const copy = async (text) => {
if (!navigator?.clipboard) return false;
try {
await navigator.clipboard.writeText(text);
setCopiedText(text);
return true;
} catch (error) {
setCopiedText(null);
return false;
}
};
return [copiedText, copy];
};
📌 Detailed Explanation - Detailed useCopyToClipboard Hook Guide
Handles large lists by populating data as the user reaches the bottom of the page, often using IntersectionObserver.
import { useEffect } from 'react';
const useInfiniteScroll = (callback, targetRef) => {
useEffect(() => {
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) callback();
}, { threshold: 1.0 });
if (targetRef.current) observer.observe(targetRef.current);
return () => observer.disconnect();
}, [callback, targetRef]);
};
📌 Detailed Explanation - Detailed useInfiniteScroll Hook Guide
That's the end of this blog,
Don't forget to check Part 2 to prepare for all the important Custom Hooks for the interview
Happy Coding :))
0
1
0