React
/Intermediate
Custom Hook Pattern
Definition
The practice of extracting reusable stateful logic from components into standalone JavaScript functions that start with 'use'.
Explain Like I'm New
If 5 different components need to know if the user is online or offline, you don't want to copy and paste the `window.addEventListener('online')` code 5 times. You write it once in a `useIsOnline()` hook, and then all 5 components can just call that one line of code.
Real World Example
Creating a `useWindowSize()` hook that returns `{ width, height }` and automatically updates whenever the browser window is resized.
Common Use Cases
- •Extracting data fetching logic
- •Abstracting complex event listeners
- •Sharing form validation logic
Interactive Example
import { useState, useEffect } from 'react'; export function useOnlineStatus() { const [isOnline, setIsOnline] = useState(true); useEffect(() => { // Setup listeners... }, []); return isOnline; }
Interview Questions
basic
- What must a custom hook's name start with?
- Can a custom hook call other hooks?
intermediate
- If two components use the same custom hook, do they share the same state?
advanced
- How do you test a custom hook?