React Patterns, Component Design, Reusability

201) What is the “props spreading” pattern and when is it useful?

Answer: Passing unknown props down to native elements for flexibility.

Example: function Input(props){ return <input {...props} /> }

Trap: Don’t accidentally spread unsafe props on DOM (like objects/functions not intended).

202) What is the “slot” pattern in React?

Answer: Expose areas using children or named props like header, footer.

Example: <Card header={<H/>} footer={<F/>}>Body</Card>

Trick: Slots = customizable layout parts.

203) What is “compound component with context” (Tabs example)?

Answer: Parent holds shared state, children consume it via context.

Example: <Tabs><Tabs.List/><Tabs.Panel/></Tabs>

Trap: Keep context value stable (memoize) to avoid re-renders.

204) What is “inversion of control” in React UI?

Answer: Parent gives control to consumer via render props or children-as-function.

Example: <Dropdown>{({open,toggle}) => ...}</Dropdown>

Trick: You give user the steering wheel.

205) How do you design a reusable Modal API?

Answer: Use isOpen, onClose, portal, focus management.

Example: <Modal isOpen={open} onClose={()=>setOpen(false)} />

Trap: Don’t forget ESC close and scroll lock.


Hooks Deep Dive & “Hard” Rules

206) Why hooks must be called in the same order?

Answer: React identifies hooks by call order; conditional calls break mapping.

Trap: if(x) useEffect() ❌

207) When does useMemo NOT help?

Answer: When calculation is cheap or dependencies change every render.

Trick: Memoization has overhead—use only for real benefit.

208) How do you avoid stale state in setInterval?

Answer: Use functional updates or store latest value in ref.

Example: setCount(c=>c+1) inside interval.

Trap: setCount(count+1) captures old count.

209) What is useId used for?

Answer: Generates stable unique IDs (good for accessibility labels).

Example:

Trick: useId = SSR-safe unique id.

210) What is useDeferredValue?

Answer: Defers updating a value to keep UI responsive (like slow filtering).

Example: const deferred = useDeferredValue(searchText);

Trap: Not a debounce; it’s priority-based deferring.


Rendering Behavior, Keys, and “Why UI Bug Happens”

211) Why key must be stable?

Answer: React uses key to keep component identity. Unstable keys cause state jumping.

Trap: key={Math.random()} ❌

212) What happens if you change a component’s key?

Answer: React remounts it (state resets).

Example: <Chat key={roomId} /> intentionally resets when room changes.

Trick: Change key = reset component.

213) Why does inline arrow function sometimes cause re-renders?

Answer: New function reference each render; memoized children see changed props.

Fix: useCallback when needed.

214) Why does inline object prop cause re-render?

Answer: New object reference each render.

Fix: useMemo or move constant outside.

215) Why do you sometimes see “Too many re-renders”?

Answer: You’re setting state during render.

Trap example: setX(1) inside component body ❌


Forms at Scale, Validation, RHF Patterns

216) Why React Hook Form is faster than controlled inputs?

Answer: It uses uncontrolled inputs + refs, reducing re-renders.

217) How do you do schema validation properly?

Answer: Use Zod/Yup on client for UX + server validation for security.

Trick: Client = convenience, Server = truth.

218) How do you handle dependent fields (country → city)?

Answer: Watch country change, reset city and refetch options.

Example: useEffect(()=>setCity(""), [country])

219) How do you handle “dirty” state in forms?

Answer: Track if user changed fields (RHF provides isDirty).

Trap: Don’t block submit incorrectly based on dirty.

220) Best practice for submit button states?

Answer: Disable on submit + show loading + prevent double submit.

Example: disabled={isSubmitting}


Data Fetching, Caching, and React Query “Interview Gold”

221) What is “stale-while-revalidate”?

Answer: Show cached data first, then refetch to update. (SWR/React Query pattern)

Trick: Fast UI + fresh data.

222) What is query key in React Query?

Answer: Unique identifier for cached data; must include parameters.

Example: ["users", page, filter]

Trap: If key misses params, cache becomes wrong.

223) What is enabled option used for?

Answer: Conditional fetching (don’t fetch until you have required data).

Example: enabled: !!userId

224) What is invalidation?

Answer: Mark cached query as outdated so it refetches after mutation.

Example: invalidateQueries(["users"])

225) Mutation vs query?

Answer: Query = get data, Mutation = change data.

Trick: Query reads, mutation writes.


Performance + UX Under Load

226) What is “optimistic update”?

Answer: Update UI immediately before server response; rollback on failure.

Example: Like button toggles instantly.

Trap: Must handle rollback correctly.

227) What is “skeleton UI” and why good?

Answer: Placeholder shape reduces perceived wait and layout shift.

Trick: Better than spinner for lists.

228) How do you handle expensive filtering for large lists?

Answer: Use startTransition, useDeferredValue, memoize computation, virtualization.

Trick: Prioritize typing, defer heavy work.

229) What’s the best way to handle huge tables?

Answer: Virtualized rows + pagination + stable row rendering (memo).

Trap: Rendering 10k rows normally will lag.

230) What is the biggest React performance mindset?

Answer: Measure first , then optimize the real bottleneck.


Testing: Practical Interview Questions

231) Why React Testing Library prefers getByRole?

Answer: It matches how users/accessibility work and leads to better tests.

Trick: Role-first testing = a11y-first UI.

232) How do you test async UI (loading → data)?

Answer: Use findBy... / waitFor to wait for UI updates.

Trap: Immediate assertions fail due to async timing.

233) How do you test a modal rendered via portal?

Answer: Ensure portal container exists in test DOM; query by role/dialog.

Example: getByRole("dialog")

234) How to test navigation in React Router?

Answer: Wrap with MemoryRouter and assert route content.

Example: <MemoryRouter initialEntries={["/users/1"]}>

235) What is MSW and why useful?

Answer: Mock network requests like real server behavior in tests.


SSR/Next.js + Hydration Edge Cases

236) Why useEffect doesn’t run on server?

Answer: Effects run after paint in browser; server render is just HTML generation.

237) How to safely access window in SSR apps?

Answer: Guard with typeof window !== "undefined" or move to useEffect.

238) Why random values cause hydration mismatch?

Answer: Server HTML differs from client render if you use Math.random() in render.

Fix: Generate on client after mount.

239) What is “client-only component” (Next.js)?

Answer: Components requiring hooks/events must run in browser ("use client").

Trick: Hooks = client.

240) When to choose SSR vs CSR for dashboards?

Answer: Usually CSR if behind auth; SSR for SEO or first paint needs.


Accessibility + Security “Panel Traps”

241) Why prefer <button> over div onClick?

Answer: Button supports keyboard, roles, focus, accessibility by default.

Trap: div needs role/tabIndex/key handlers.

242) How do you manage focus when a modal opens?

Answer: Focus first interactive element; trap focus; restore focus on close.

Trick: Open → focus in, Close → focus back.

243) What is aria-label vs label?

Answer: Real <label> is best for inputs. aria-label is fallback for elements without visible label.

244) What is the danger of dangerouslySetInnerHTML?

Answer: XSS if content is untrusted. Must sanitize input.

245) What’s a safe way to render user content?

Answer: Render as text (React escapes by default). Only render HTML if sanitized.


Practical “How would you build…” Questions

246) How would you build an infinite scroll?

Answer: Use IntersectionObserver at bottom sentinel + fetch next page + store pages.

Trap: Avoid duplicate requests; handle hasMore.

247) How would you build a search with debounce + caching?

Answer: Debounce input, use query key by term, cache results (React Query).

Trick: Key = ["search", term].

248) How would you build toast notifications?

Answer: Global toast provider + queue state + auto-dismiss timer; render via portal.

Trap: Cleanup timers on unmount.

249) How would you build role-based UI (RBAC)?

Answer: Auth state includes roles → guard routes + hide/show features + server enforces permissions.

Trap: Frontend-only RBAC is not security.

250) How would you explain your React project in interview?

Answer: Use this structure: Problem → Users → Key features → Tech choices → Hard bug → Result → Next improvements .

Trick: Keep it 60–90 seconds, then offer deeper details.

Last updated