Advanced Hooks, Refs, and DOM Control

Advanced Hooks, Refs, and DOM Control

101) What is useRef used for?

Answer: It stores a mutable value that persists across renders without causing re-renders, and it can hold DOM references .

Example:

const inputRef = useRef(null);
<input ref={inputRef} />

Trick: Ref = remember without re-render.

102) useRef vs useState?

Answer: useState triggers re-render on update; useRef does not.

Example: ref.current++ won’t re-render.

103) How do you focus an input on button click?

Answer: Use ref and call .focus().

Example:

const ref = useRef();
<button onClick={() => ref.current.focus()}>Focus</button>
<input ref={ref} />

Trap: Ensure the element exists before calling focus.

104) What is forwardRef and why use it?

Answer: It allows a parent to pass a ref into a child component’s DOM element.

Example:

Trick: forwardRef = “ref goes through component.”

105) What is useImperativeHandle?

Answer: It customizes what the parent can access via ref (expose methods, hide DOM).

Example:

Memory: ImperativeHandle = controlled ref API.

106) useEffect vs useLayoutEffect?

Answer: useEffect runs after paint ; useLayoutEffect runs before paint (synchronous), good for measuring layout.

Trap: useLayoutEffect can block rendering—use only when necessary.

107) When should you use useLayoutEffect?

Answer: When you must measure DOM and update before the user sees layout (avoid flicker).

Example: measure element width and set state.

108) What is a custom hook?

Answer: A function starting with use that reuses stateful logic across components.

Example: useDebounce(value, delay)

Trick: Custom hook = reusable logic, not UI.

109) Can hooks be called conditionally?

Answer: No. Hooks must run in the same order every render.

Trap: if (x) useEffect(...) ❌

110) How do you share logic between components without prop drilling?

Answer: Use composition, custom hooks, or Context for shared data.

Memory: UI reuse = components; logic reuse = hooks.


Side Effects, Timers, and Cleanup

111) How do you implement debounce in React?

Answer: Use useEffect with a timeout and cleanup.

Example:

Trick: Debounce = wait until silence.

112) How do you implement throttle in React?

Answer: Store last time in ref and block calls until interval passes.

Trap: Using state for timestamps can cause extra re-renders.

113) What is a memory leak in React effects?

Answer: When effects keep subscriptions/timers alive after component unmounts.

Fix: cleanup function.

114) “State update on unmounted component” — why happens?

Answer: Async code completes after unmount and calls setState.

Fix: cleanup flag or AbortController.

115) How to handle async in useEffect cleanly?

Answer: Define an inner async function; don’t make effect callback async directly.

Example:

116) Why is useEffect(async () => {}) not recommended?

Answer: Because useEffect expects cleanup or nothing, but async returns a Promise (not a cleanup).

Memory: Effect return must be cleanup function.

117) How do you handle subscriptions (websocket/events)?

Answer: Subscribe in effect, unsubscribe in cleanup.

Example: socket.on(...) → socket.off(...)

118) How can you avoid re-fetching on every render?

Answer: Put fetch logic inside useEffect with stable dependencies, or use React Query/SWR.

119) What is “effect dependency trap”?

Answer: Putting an unstable value in deps (like inline function/object) causes effect to re-run endlessly.

Fix: useCallback/useMemo or move logic inside effect.

120) What is Strict Mode double-invocation impact?

Answer: Effects may run twice in development to surface side effects. Your effect must be idempotent and properly cleaned up.


Portals, Modals, and UI Layering

121) What is a React Portal?

Answer: It renders children into a DOM node outside the parent hierarchy (great for modals/tooltips).

Example: createPortal(<Modal/>, document.body)

Trick: Portal = render here, place there.

122) Why use Portal for modals?

Answer: Avoids z-index/overflow issues from parent containers and keeps layering consistent.

123) Does event bubbling work through portals?

Answer: Yes—events bubble through the React tree, not just DOM placement.

Trap: People assume portal breaks events.

124) How do you close modal on outside click?

Answer: Use overlay click handler + stop propagation in modal content.

Example:

125) How do you prevent body scroll when modal opens?

Answer: Set document.body.style.overflow = "hidden" in effect, and restore in cleanup.


Error Boundaries & Reliability

126) What is an Error Boundary?

Answer: A component that catches rendering errors in child components and shows fallback UI.

Trick: Error boundary catches render errors, not async.

127) Can function components be error boundaries?

Answer: Not directly with classic API; error boundaries are typically class components, or use libraries.

128) What errors do error boundaries NOT catch?

Answer: Errors in event handlers, async code (promises), server-side rendering errors.

Fix: handle with try/catch in async, global handlers, etc.

129) Why are error boundaries important in production?

Answer: They prevent entire app crash and allow graceful fallback and logging.

130) How do you log errors from error boundary?

Answer: Use componentDidCatch(error, info) to report to monitoring (Sentry etc.).


React 18 Concepts: Concurrency, Transitions, Suspense

131) What changed in React 18 about rendering?

Answer: Introduced concurrent features and improved batching; transitions help keep UI responsive.

132) What is “automatic batching”?

Answer: React batches multiple state updates together even outside events (like timeouts/promises) in React 18.

Trick: Batching = fewer renders.

133) What is startTransition?

Answer: Marks non-urgent updates (like filtering a big list) so urgent updates (typing) stay fast.

Example:

Memory: Transition = “not urgent”.

134) When should you use transitions?

Answer: For expensive UI updates triggered by user input, to avoid lag.

135) What is useTransition?

Answer: Hook that provides isPending + startTransition for transitions with loading state.

Example: const [isPending, startTransition] = useTransition();

136) What is Suspense in React?

Answer: It shows fallback while something is “suspending” (lazy components, certain data fetch patterns).

Example:

137) What is React.lazy?

Answer: Code-splits a component and loads it on demand. Works with Suspense.

138) What is Suspense NOT for by default?

Answer: Plain fetch in useEffect doesn’t integrate with Suspense automatically unless you use a Suspense-aware data layer.

139) What is streaming SSR conceptually?

Answer: Server can send HTML in chunks; Suspense boundaries can stream fallback then real content when ready (framework feature).

Trick: Stream = faster first paint.

140) Common trap with Suspense?

Answer: Forgetting fallback boundaries or assuming it handles all data fetching without proper setup.


Testing, Quality, and Interview-Ready Practices

141) How do you test React components?

Answer: Use React Testing Library (RTL) to test behavior like user sees; Jest/Vitest as runner.

Trick: Test behavior, not implementation.

142) What should you avoid testing in React?

Answer: Internal state details and private functions; focus on rendered output and interactions.

143) How do you mock API calls in tests?

Answer: Mock fetch, or use MSW (Mock Service Worker) to mock network requests realistically.

144) What is a “unit test” vs “integration test” in React?

Answer: Unit: small component/function. Integration: multiple components working together (routing, API, context).

145) What is the best way to select elements in RTL?

Answer: Prefer accessible queries: getByRole, getByLabelText, getByText.

Memory: Role-first = accessibility-first.

146) How do you test a form submission?

Answer: Fill inputs and click submit using userEvent, assert results (error messages or API call).

Trap: Using fireEvent only; userEvent is closer to real behavior.

147) What is a controlled vs uncontrolled component testing difference?

Answer: Controlled: update via change events and assert state reflected in UI. Uncontrolled: assert ref/submit values.

148) What is a common React security mistake?

Answer: Using dangerouslySetInnerHTML with untrusted input → XSS risk.

Trick: If you must, sanitize.

149) What is hydration mismatch?

Answer: Server-rendered HTML doesn’t match client render, causing warnings and re-render.

Fix: Ensure same initial data and avoid random values during SSR.

150) What’s the best “interview answer” for handling large apps?

Answer: Use good component boundaries, predictable state (local → lifted → context/store), caching (React Query), code splitting, and performance profiling.

Last updated