Hooks Interview Questions
What are hooks? What are the rules of hooks?
Functions starting with use that let function components use state, effects, context and refs. Rules: call them only at the top level (not in loops/conditions) and only from components or custom hooks.
useEffect dependency array: none vs [] vs [a]?
| Array | Runs |
|---|---|
| none | after every render |
| [] | once after mount (cleanup on unmount) |
| [a] | after mount and whenever a changes |
useMemo vs useCallback?
Both memoize between renders. useMemo caches the result of a function (a value); useCallback caches the function itself. useCallback(fn, deps) is the same as useMemo(() => fn, deps).
useRef vs useState?
Changing state re-renders; changing ref.current does not. Use refs for DOM nodes, timer ids and values not shown in the UI.
useEffect vs useLayoutEffect?
useEffect runs after the browser paints; useLayoutEffect runs after DOM updates but before paint (blocking). Use the layout version only to measure the DOM and avoid flicker.
Why does my effect run twice in development?
React StrictMode mounts, unmounts and mounts components again in development to reveal missing cleanup functions. It does not happen in production.
What is a custom hook?
A function named useXyz that calls other hooks to share stateful logic (useFetch, useDebounce, useAuth). Each component that uses it gets its own independent state.