Skip to main content
Practice Problems

What are custom hooks in React

Custom Hooks are user-defined functions that use built-in React hooks (useState, useEffect, useMemo, etc.) to encapsulate and reuse logic across different components.

Main rule: custom hook name must start with use so React understands it's a hook and applies corresponding rules.


Why Custom Hooks?

Logic encapsulation

You can extract related business logic (e.g., API work, forms, timers) into separate hook and use it in multiple places.

Avoiding duplication

Instead of repeating same useEffect or useState in multiple components, you write hook once and reuse it.

Improving readability

Components become smaller and cleaner if main logic is extracted into hooks.


Simple Custom Hook Example

Before: without custom hook

jsx
function Component() { const [width, setWidth] = useState(window.innerWidth); useEffect(() => { const handleResize = () => setWidth(window.innerWidth); window.addEventListener("resize", handleResize); return () => window.removeEventListener("resize", handleResize); }, []); return <p>Width: {width}px</p>; }

After: with custom hook

jsx
function useWindowWidth() { const [width, setWidth] = useState(window.innerWidth); useEffect(() => { const handleResize = () => setWidth(window.innerWidth); window.addEventListener("resize", handleResize); return () => window.removeEventListener("resize", handleResize); }, []); return width; } // Usage function Component() { const width = useWindowWidth(); return <p>Width: {width}px</p>; }

Where Custom Hooks Are Used

  • API work (e.g., useFetch, useUserData)
  • Form management (useForm, useInput)
  • Modal, tooltip states (useModal)
  • Local storage work (useLocalStorage)
  • Timers, intervals (useInterval, useDebounce)
  • External library integration (useSocket, useMap)

useLocalStorage Hook Example

jsx
function useLocalStorage(key, initialValue) { const [value, setValue] = useState(() => { const item = localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; }); useEffect(() => { localStorage.setItem(key, JSON.stringify(value)); }, [key, value]); return [value, setValue]; } // Usage const [theme, setTheme] = useLocalStorage("theme", "light");

Conclusion:

Custom hooks make your code reusable, readable and clean. They help extract repeating logic from components and organize application architecture.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems