React
react Interview Questions and Answers
1. What is React?
A: A JavaScript library for building user interfaces, focusing on building UI components declaratively.
2. Who developed React?
A: Facebook (now Meta).
3. What is JSX?
A: JavaScript syntax extension that lets you write HTML-like code inside JS. Compiled to React.createElement.
4. Example of JSX?
5. Why use keys in lists?
A: Helps React identify which items changed, added or removed, improving diffing & reconciliation.
6. What is a component?
A: A reusable piece of UI. Can be class or function.
7. Difference between functional and class components?
- Functional: simple functions, with hooks for state/lifecycle.
- Class: E6 classes with render method and lifecycle methods.
8. What is a prop?
A: Short for properties. Read-only data passed from parent to child.
9. How to pass data from parent to child?
Access with props.name
.
10. Can props change inside a component?
A: No. Props are immutable from the child’s perspective.
11. What is state?
A: Data managed inside a component that can change over time.
12. How to declare state in functional component?
13. How to update state in class component?
14. Why not modify state directly?
A: Direct mutation bypasses React's update mechanism, so UI won’t re-render properly.
15. What is lifecycle in React?
A: Series of methods invoked at different stages of component existence (mounting, updating, unmounting).
16. Example of a lifecycle method?
17. What replaces lifecycle methods in functional components?
A: Hooks like useEffect.
18. What is useEffect?
A: Hook that performs side effects like fetching data, subscriptions, manually changing the DOM.
19. Basic example of useEffect?
20. How to run useEffect only on mount?
21. How to run code on unmount?
22. What happens if you forget dependency array?
A: useEffect runs after every render.
23. How to trigger effect on specific variable change?
24. How to handle events in React?
25. Why onClick not onclick?
A: React uses camelCase for event handlers.
26. How to handle form input?
27. What is controlled vs uncontrolled component?
- Controlled: React state drives input value.
- Uncontrolled: Uses DOM state via ref.
28. How to conditionally render?
29. How to render multiple components?
or <React.Fragment>
.
30. Why use key in a list?
A: Helps React identify items to minimize re-rendering.
31. What is a hook?
A: Special function that lets you hook into React features (state, lifecycle, context) from functional components.
32. Name some built-in hooks.
- useState
- useEffect
- useContext
- useReducer
- useRef
- useMemo
- useCallback
33. What is useContext?
A: Lets you subscribe to React context without nesting consumers.
34. What is useReducer?
A: Alternative to useState for complex state logic.
35. What is useMemo?
A: Memoizes expensive computations.
36. What is useCallback?
A: Returns memoized callback, prevents unnecessary re-creations.
38. What is React Context?
A: Way to pass data through component tree without props drilling.
39. How to create a Context?
40. How to use Context Provider?
41. How to consume context?
42. What is React.memo?
A: HOC that memoizes functional components.
43. What is shouldComponentUpdate?
A: Class lifecycle to prevent unnecessary render.
44. What is React.lazy?
A: Code splitting by dynamically loading components.
45. Example of React.lazy with Suspense?
46. What is Jest?
A: JavaScript testing framework by Facebook, often used for React.
47. What is React Testing Library?
A: Tool for testing React components by querying DOM like a user.
48. How to test a click event?
49. Why is React called declarative?
A: You describe what UI should look like, React figures out how to update DOM.
### 50. What is virtual DOM?
A: Lightweight JS representation of DOM. React diffs it to optimize real DOM updates.
51. What is hydration?
A: Process where React takes over static HTML (SSR) and makes it interactive.
52. What is reconciliation?
A: Process by which React updates DOM with virtual DOM diff.
53. What is prop drilling?
A: Passing props through many layers just to get to a deeply nested component.
54. How to solve prop drilling?
A: Context API, Redux or similar state management.
55. What is React Router?
A: Library for routing in React apps.
56. Basic routing example?
57. How to navigate programmatically?
58. What is Redux?
A: Predictable state container for JS apps.
59. What is store in Redux?
A: Holds entire app state.
60. What are actions in Redux?
A: Plain objects describing what happened.
61. What is a reducer?
A: Pure function describing how state changes.
62. What is middleware in Redux?
A: Enhances dispatch (e.g., redux-thunk, redux-saga).
63. What is connect?
A: HOC from react-redux to link state & dispatch to props.
64. What are useSelector & useDispatch?
A: React hooks to read from store and dispatch actions.
65. How to type props?
66. How to type state with useState?
67. How to type useRef?
68. What happens if you update state multiple times in same tick?
A: Both run with same count, so only increment once.
69. How to avoid above issue?
70. What are controlled vs uncontrolled inputs?
- Controlled: value tied to React state.
- Uncontrolled: uses DOM internal state via ref.
71. What is dangerouslySetInnerHTML?
A: Lets you set HTML directly but may expose XSS risks.
72. What happens if you forget key in a list?
A: React warns, may have inefficient renders.
73. Can you use multiple useEffect?
A: Yes. Each runs independently.
74. Can hooks be inside loops or conditions?
A: No. Must be at top level to preserve order.
75. What is StrictMode?
A: Helps highlight potential problems in app during development.
76. Why avoid using index as key?
A: Breaks component identity on reorder, causes unexpected behavior.
77. What is an error boundary?
A: A React component that catches JavaScript errors anywhere in its child component tree, logs them, and displays a fallback UI.
78. How to create an error boundary?
Must be a class component implementing:
79. Can hooks catch errors?
A: No, hooks can’t catch errors like Error Boundaries—must still wrap with a class boundary.
80. What is useLayoutEffect?
A: Same signature as useEffect, but fires synchronously after all DOM mutations (before browser paint).
81. When to prefer useLayoutEffect?
A: For measuring layout or synchronously mutating DOM to avoid flicker.
82. What is useImperativeHandle?
A: Customizes value exposed to parent when using ref.
83. What is a custom hook?
A: A function starting with use that can call other hooks to encapsulate reusable logic.
84. Example of a custom hook?
85. What is Suspense?
A: Allows waiting for some code or data to load and declaratively shows fallback.
86. Can Suspense handle data fetching today?
A: Only with libraries (Relay, SWR, React Query). Native data Suspense still experimental.
87. What is concurrent rendering?
A: React can interrupt rendering to prioritize updates, improving responsiveness.
88. What is SSR in React?
A: Render components to HTML on server, send to browser to hydrate. Faster initial load & better SEO.
89. What is hydration?
A: Attaching React event listeners to server-rendered HTML.
90. How does Next.js help with React SSR?
A: Automates routing, data fetching, and server-side rendering.
91. What is getStaticProps?
A: Next.js function to fetch data at build time for static generation.
92. What is getServerSideProps?
A: Fetches data on every request on the server.
93. What is API Routes in Next.js?
A: Lets you write backend functions in /pages/api.
94. What is tree shaking in React apps?
A: Removes unused code during bundling to reduce bundle size.
95. What does webpack do?
A: Bundles JS, CSS, images into optimized files.
96. What is code splitting?
A: Split app into smaller chunks loaded on demand.
97. What is React.StrictMode used for?
A: Activates additional checks and warnings for descendants in development.
98. How to lazy load image?
99. What is Helmet in React?
A: Library to manage changes to document head, like title and meta tags.
100. What is PropTypes?
A: Library for type-checking props in development.
101. Can you use hooks inside conditions or loops?
A: No. Hooks must run in same order every render. Only call at top level of component.
102. How to handle async in useEffect?
A: Use an inner async function:
103. What happens if you omit dependencies in useEffect?
A: Effect might use stale values from old closures.
104. How to skip effect on first render?
105. Why might you see “Too many re-renders” error?
A: State updater is called directly during render (in component body, not in effect/handler).
106. When to use useReducer over useState?
A: When state logic is complex or depends on previous state.
107. How to combine useReducer with Context?
Create context provider with reducer and dispatch:
108. How to memoize context value to prevent re-renders?
109. What is forwardRef?
A: Lets you pass ref through a component to a DOM node.
- How to expose methods via ref? Use useImperativeHandle:
111. What is React Query?
A: Powerful library for fetching, caching, synchronizing server state.
112. Example using useQuery?
113. How does React Query differ from Redux?
- Manages server state, not global client state.
- Automatic caching, retries, invalidation.
114. What is stale time vs cache time?
- staleTime: how long data is fresh.
- cacheTime: how long inactive data stays in cache.
115. Can React Query work with Suspense?
A: Yes, with suspense: true config.
116. What is React Testing Library (RTL)?
A: Library to test React components by interacting with DOM as user would.
117. What is the philosophy of RTL?
A: Avoid testing implementation details. Focus on output & behavior.
118. Example of RTL rendering a component?
119. How to simulate click with RTL?
120. How to use waitFor?
121. What is aria-*
?
A: Attributes to improve accessibility for assistive tech (screen readers).
122. How to hide visually but keep accessible?
123. Why prefer button over clickable div?
A: Buttons are keyboard & screen reader friendly by default.
124. How to ensure focus order?
Use logical DOM order + tabIndex.
125. What is role attribute for?
Helps assistive tech understand element’s purpose.
126. How to type functional component props?
127. How to type state?
128. How to type useReducer?
129. How to type ref?
130. What is as const?
Locks object to literal types.
131. What is Zod?
A: TypeScript-first schema validation library.
132. How to validate object with Zod?
133. How to integrate with React forms?
Call schema.safeParse
on submit.
134. What is compound component pattern?
A: Components designed to work together by sharing state via context.
135. What is render props pattern?
A: Pass a function as child to control rendering.
136. What is HOC?
A: Function that takes component and returns enhanced component.
137. Example of simple HOC?
138. Difference HOC vs custom hook?
- HOC: wraps component.
- hook: reusable logic for functional components.
139. What is a controlled vs uncontrolled component?
- Controlled: React state is source of truth.
- Uncontrolled: relies on DOM, accessed via ref.
140. What is slots pattern?
Mimics children injection like <Dialog><DialogTitle/><DialogContent/></Dialog>
141. Why is virtual DOM faster?
A: Minimizes costly direct DOM operations by batching diff and updating only changed nodes.
142. How does reconciliation algorithm work?
A: Compares new vs old virtual tree and updates only what changed.
143. What is hydration mismatch warning?
A: SSR HTML differs from first client render—can break event bindings.
144. What are React fibers?
A: Internal data structure enabling incremental rendering.
145. Why do stale closures happen?
A: useEffect captures values at render time. Can reference outdated variables.
146. What is ESLint plugin for React?
A: eslint-plugin-react + eslint-plugin-react-hooks
.
147. What is Prettier used for?
A: Code formatter ensuring consistent style.
148. How to prevent unnecessary re-renders?
A: Use React.memo, useCallback, useMemo
.
149. What is Suspense fallback for?
A: UI shown while lazy-loaded component or data is loading.
150. What is code splitting?
A: Breaks bundle into smaller chunks loaded on demand.
151. What’s new in React 18?
A:
- Automatic batching
- startTransition
- Concurrent features
- New SSR APIs
152. What is automatic batching?
A: Groups multiple state updates into a single render, even inside timeouts or promises.
153. What is startTransition?
A: Marks UI update as non-urgent, so React can interrupt for higher priority work.
154. What is useDeferredValue?
A: Lets you defer updating a value until browser is idle, useful for expensive calculations.
155. What is useId?
A: Generates unique ids for accessibility or SSR consistency.
156. What is a React Portal?
A: Renders children into a DOM node outside of parent hierarchy.
157. When use portals?
A: For modals, tooltips, dropdowns that visually break out of parent container.
158. What is React DevTools profiler?
A: Tool to record performance, see component re-renders and flame graphs.
159. How to find unnecessary renders?
A: Profile in React DevTools, look for frequent renders without prop or state change.
160. Why enable React StrictMode?
A: Helps find side effects by double-invoking certain functions in development.
161. How to build infinite scroll?
- Use IntersectionObserver to detect when near bottom.
- Load more data and append.
162. How to debounce input in React?
163. How to implement optimistic UI?
A: Immediately update UI, then send API call, rollback if fails.
164. Example of optimistic update?
165. What is skeleton loading?
A: Show placeholder shapes while loading data.
166. How does Zustand compare to Redux?
A: Lightweight, no boilerplate reducers, direct mutations.
167. How does Recoil work?
A: Atom-based state that can be shared across components with derived selectors.
168. What is Jotai?
A: Minimal atomic state library, simpler than Recoil.
169. How to deploy React on Netlify?
- Push to GitHub
- Connect repo on Netlify
- It auto builds with npm run build
170. How about Vercel?
Similar process, Vercel optimizes for Next.js but also works for pure React.
171. Why set homepage in package.json?
A: Ensures correct relative paths for static assets in single-page apps.
172. How to avoid 404 on refresh in SPA?
Use Netlify’s _redirects: bash CopyEdit /* /index.html 200
175. How to test reducer with Jest?
176. What is Cypress?
A: End-to-end testing framework that tests actual browser interactions.
177. What is error fallback UI?
Use ErrorBoundary to render fallback when component fails.
178. How to handle stale props in async?
Wrap callback in useCallback with stable deps or track a version ref.
179. Example of AbortController in React?
180. Why wrap API calls inside useEffect?
A: To avoid re-running on every render.
181. How to type generic prop children?
182. How to type forwarded refs?
183. How to type reducer actions?
184. What is Formik?
A: Popular form library handling state, validation, touched, errors.
185. What is React Hook Form?
A: Hooks-based form management with minimal re-renders.
186. How to integrate Zod + React Hook Form?
187. Difference between controlled & uncontrolled form in RHF?
A: Controlled uses watch & setValue; uncontrolled registers inputs with refs.
188. What is ISR in Next.js?
A: Incremental Static Regeneration, rebuilds static pages on demand.
189. What is SSG vs SSR vs CSR?
- SSG: Static site generation at build.
- SSR: Render on every request.
- CSR: Only in browser.
190. How to protect SSR pages?
Check cookies/session inside getServerSideProps.
191. Build a counter with useReducer?
192. How to debounce input with hooks?
Use useEffect and setTimeout.
193. How to throttle scroll?
Use setTimeout inside onScroll, or external lodash.throttle.
194. Build custom hook useToggle?
195. How to persist state to localStorage?
196. How does key impact reconciliation?
A: Helps React track changes—bad keys cause unnecessary unmount/remount.
197. Why clone element?
To inject props or modify children.
198. What is dangerouslySetInnerHTML?
Renders raw HTML, often for CMS data. Must sanitize to avoid XSS.
199. What is hydration mismatch?
Rendered HTML from SSR doesn’t match client render—throws warning.
200. Why is React declarative?
A: You specify what UI should look like based on state. React handles how to update efficiently.
201. What is useTransition?
A: A React hook to mark state updates as non-urgent, allowing urgent updates (like typing) to interrupt.
202. Difference useTransition vs startTransition?
- useTransition: in components, returns startTransition + pending state.
- startTransition: standalone utility, e.g. inside event handlers.
203. What is concurrent mode?
A: Lets React prepare multiple versions of UI at the same time, pausing work to keep app responsive.
204. What is React Server Components (RSC)?
A: Components that render on server, send minimal payload to client (no JS bundle needed for them).
205. Does Suspense for data fetching work natively?
A: Experimental. Most apps use libraries like Relay or React Query.
206. How does SWR differ from React Query?
- SWR: smaller, auto revalidation.
- React Query: more features (pagination, mutations, devtools).
207. What is stale-while-revalidate?
A: Show cached data, fetch new data in background.
208. How to refetch manually in React Query?
209. What does onSuccess vs onSettled mean?
- onSuccess: runs if request succeeds.
- onSettled: runs on both success or error.
210. How to poll with React Query?
211. What is Yup?
A: JavaScript schema validation library often used with Formik or RHF.
212. Difference Zod vs Yup?
- Zod: fully TypeScript-first.
- Yup: JS-first, can infer types.
213. How to validate email with Zod?
214. What is Controller in React Hook Form?
A: Wraps controlled components (like MUI, Antd) to connect with RHF.
215. What is setValue in RHF?
A: Imperatively sets input value in the form state.
216. What is Tailwind CSS?
A: Utility-first CSS framework. Use className with many tiny classes.
217. How to integrate Tailwind with CRA?
Install then @import 'tailwindcss/base'; in index.css.
218. How to conditionally add Tailwind classes?
219. What is Headless UI?
A: Library of unstyled accessible components for Tailwind + React.
220. How does classnames library help?
A: Conditionally build className strings.
221. How does Next.js routing work?
A: File-based. A file pages/about.js becomes /about
.
222. What is API Route?
A: Any file in pages/api becomes serverless endpoint.
223. What is middleware in Next.js?
A: Run code (auth, redirects) before request completes.
224. How to enable ISR (Incremental Static Regeneration)?
225. How to fetch user data on server in Next.js?
Use getServerSideProps.
226. What is XState?
A: Library for building, visualizing, interpreting finite state machines/statecharts.
227. Advantage of state machines over useState?
Prevents invalid state by defining allowed transitions.
228. How to integrate XState with React?
Use useMachine hook from @xstate/react.
229. Can XState work with Next.js?
Yes, for global or persisted state across pages.
230. What is lazy hydration?
A: Delay hydrating non-critical React components until idle.
231. How to defer hydration in Next.js?
Use next/dynamic with ssr: false.
232. What is prefetch in Next.js?
Links auto prefetch pages in viewport.
233. What is code splitting by component?
Use React.lazy to split large components.
234. Why measure bundle size?
Avoid slow load time. Use tools like source-map-explorer.
235. What is long task blocking?
JS running >50ms delays input responsiveness.
236. Why use semantic tags (<button>
, <nav>
, etc)?
Improves screen reader and keyboard nav. <div onClick>
is not keyboard accessible.
237. What is skip link?
Link at top for keyboard users to jump to main content.
238. How to make modal accessible?
- Trap focus inside modal.
- Restore focus on close.
- Use aria-modal.
239. Why use aria-live?
Announce dynamic content changes to screen readers.
240. How to audit a11y?
Use Lighthouse or axe DevTools.
241. How to persist auth token in React?
Use localStorage or HTTP-only cookies (server).
242. How to cancel API call on unmount?
Use AbortController inside useEffect.
243. How to combine refs?
Use mergeRefs util or write your own combining forwardRef.
244. What is prop getter pattern?
Return props to spread on elements to manage state (common in headless UI).
245. What is compound components pattern?
Components like <Tabs><Tabs.List/><Tabs.Panel/></Tabs>
, sharing state via context.
246. What is React DevTools highlight updates?
Shows re-render boundaries in UI.
247. What is Storybook?
Isolated UI component explorer for React.
248. How to automate tests in CI?
Run npm test in GitHub Actions or similar.
249. How to deploy Next.js on Vercel?
Just connect repo — optimized for SSR.
250. What is .env.local?
Environment variables only for local dev (not pushed to production).
251. What is getInitialProps?
A: Legacy data fetching method runs on server and client. Replaced by getStaticProps / getServerSideProps.
252. Difference getStaticProps vs getServerSideProps vs getInitialProps?
- getStaticProps: static at build time.
- getServerSideProps: runs on each request.
- getInitialProps: old, runs on server or client.
253. What is Next.js Middleware?
A: Runs before request hits page — good for auth, redirects, headers.
254. What is Edge Runtime in Next.js?
A: Middleware runs at edge locations for lower latency.
255. What is Streaming SSR (React 18)?
A: Send HTML chunks as they’re generated, improves TTFB (time to first byte).
256. How to handle i18n in Next.js?
Use next-i18next
or built-in i18n
config in next.config.js
.
257. How to manage translations in React?
Use libraries like react-i18next.
258. What is a namespace in i18next?
Group of translation keys for modular loading.
259. What is guards in XState?
A: Conditions that determine if a transition should occur.
260. What are invoked services in XState?
A: Handle promises/observables inside state machine, automatically handle success/fail.
261. Why use state machines for forms?
Prevents illegal states like “submitted while loading.”
262. What is micro-frontend architecture?
A: Split UI into independently deployable smaller apps.
263. How to share state between micro-frontends?
Use global events or state libraries like zustand with storage.
264. What is multi-tenant app?
A: Single app serving multiple clients with isolated data/custom themes.
265. What is Radix UI?
A: Primitives for building accessible, unstyled UI components.
266. How does Chakra UI differ?
A: Component library with theme system, heavily styled by default.
267. What is styled-system?
A: Utility for building responsive, theme-based style props.
268. What is Emotion vs Styled Components?
Both CSS-in-JS. Emotion tends to be faster, smaller runtime.
269. How to animate in React?
Use framer-motion for declarative animations.
270. How to build dark mode toggle?
Use CSS vars with class toggle, or libraries like use-dark-mode.
271. What is queryKey in React Query?
Unique identifier to cache and refetch.
272. What does keepPreviousData do?
Keeps previous results during new request, prevents flicker.
273. What is select option in useQuery?
Transforms data before returned to component.
274. How does SWR handle caching?
Stores in global cache; auto revalidates on focus / network reconnect.
275. How to persist React Query cache across reloads?
Use persistQueryClient plugin.
276. How to test custom hooks?
Use @testing-library/react-hooks
or render inside test component.
277. How to mock React Router?
Use MemoryRouter in tests.
278. How to snapshot test with Jest?
279. Why prefer user-event over fireEvent?
Simulates more realistic user actions (tabbing, typing delays).
280. How to measure test coverage?
Run jest --coverage
.
281. What is preview deployment?
Each PR deploys to unique URL (Vercel, Netlify), great for QA.
282. How to optimize build times?
Cache node_modules & Next.js cache in CI.
283. What does next build
do?
Compiles app, generates static HTML + CSS.
284. Why `NODE_ENV=production matters?
Enables React production optimizations.
285. What is SWC in Next.js?
Rust compiler replacing Babel for faster builds.
286. How to avoid prop drilling without context?
Use zustand, jotai, or event emitters.
287. How to prevent layout shift?
Use fixed image dimensions (or Next.js <Image>
).
288. What is hydration mismatch error?
Client and server HTML differ—causes warning or broken hydration.
289. How to track performance in React?
Use useTraceUpdate, React Profiler, or tools like Sentry for slow transactions.
290. How to lazy load component only on client?
291. Write a hook that toggles boolean on interval.
292. Build pagination with React Query.
Pass page param to queryKey.
293. Build modal with escape to close.
Use useEffect
to listen for keydown
Escape.
294. How to persist state with localStorage + SSR safe
?
Check window:
295. How to debounce search input?
Use useEffect + setTimeout
.
296. How to skip hydration of client-only widget
?
Wrap in {typeof window !== 'undefined' && <Widget />}
.
297. What’s the biggest React perf anti-pattern
?
Updating state or context in render. Or spreading large objects triggering re-renders.
298. When to memoize component with React.memo
?
When renders are costly and props rarely change.
299. How to visualize re-renders?
Use why-did-you-render
package.
300. What excites you most about React’s future?
Concurrent rendering, server components, auto memoization, smaller bundles with RSC.