React Hooks Custom Hooks 3 — Questions and Answers
Question 1: What is the purpose of a useDebounce custom hook?
- To delay rendering until all state updates complete
- To delay updating a value until the user stops changing it for a specified time (Correct answer)
- To batch multiple dispatches
- To throttle API polling intervals
Correct answer: To delay updating a value until the user stops changing it for a specified time
useDebounce delays propagating a value change until a quiet period elapses, reducing rapid-fire side effects.
Question 2: How does a usePrevious custom hook work?
- It returns the initial state value
- It stores the current value in a ref after each render and returns the previous render's value (Correct answer)
- It caches the component's first render output
- It uses localStorage to persist the previous value
Correct answer: It stores the current value in a ref after each render and returns the previous render's value
A useEffect inside the hook updates the ref after each render, so the ref holds the value from the previous render.
Question 3: What is a useOnClickOutside custom hook typically used for?
- Detecting clicks inside a modal
- Detecting clicks outside a referenced element to close dropdowns or modals (Correct answer)
- Tracking all click coordinates
- Preventing event bubbling
Correct answer: Detecting clicks outside a referenced element to close dropdowns or modals
useOnClickOutside attaches a document click listener and fires a callback when the click target is outside the given ref.
Question 4: Why should custom hooks avoid directly modifying DOM nodes without going through React?
- It's a syntax error
- Imperative DOM mutations can conflict with React's virtual DOM reconciliation (Correct answer)
- React automatically reverts any direct mutations
- Direct DOM access is unavailable in hooks
Correct answer: Imperative DOM mutations can conflict with React's virtual DOM reconciliation
React controls the DOM via reconciliation; bypassing it with direct mutations can cause inconsistencies and bugs.
Question 5: How does a useToggle custom hook differ from a plain useState(false) call?
- useToggle stores the value in a ref
- useToggle encapsulates the toggle logic so consumers only get [value, toggle] without managing the setter (Correct answer)
- useToggle persists state to sessionStorage
- There is no practical difference
Correct answer: useToggle encapsulates the toggle logic so consumers only get [value, toggle] without managing the setter
useToggle hides the setter and exposes a stable toggle function, reducing boilerplate in every consumer.
Question 6: What React utility can you use to create a stable function reference to expose from a custom hook?
- useMemo
- useCallback (Correct answer)
- useRef
- useId
Correct answer: useCallback
useCallback memoizes the function so the same reference is returned across renders unless dependencies change.
What is the purpose of a useDebounce custom hook?