D DevBrainBox

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?

const element = <h1>Hello, world!</h1>;

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?

<Child name="Alice" />

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?

const [count, setCount] = useState(0);

13. How to update state in class component?

this.setState({ count: this.state.count + 1 });

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?

componentDidMount() {
  console.log('Component mounted');
}

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?

useEffect(() => {
  console.log('Runs on mount & update');
});

20. How to run useEffect only on mount?

useEffect(() => {
  console.log('Runs once');
}, []);

21. How to run code on unmount?

useEffect(() => {
  return () => console.log('cleanup');
}, []);

22. What happens if you forget dependency array?

A: useEffect runs after every render.

23. How to trigger effect on specific variable change?

useEffect(() => {
  console.log('Runs when count changes');
}, [count]);

24. How to handle events in React?

<button onClick={handleClick}>Click</button>

25. Why onClick not onclick?

A: React uses camelCase for event handlers.

26. How to handle form input?

<input value={text} onChange={e => setText(e.target.value)} />

27. What is controlled vs uncontrolled component?

  • Controlled: React state drives input value.
  • Uncontrolled: Uses DOM state via ref.

28. How to conditionally render?

{isLoggedIn ? <Dashboard /> : <Login />}

29. How to render multiple components?

<>
 <Header />
 <Content />
</>

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.

const value = useMemo(() => computeExpensive(a,b), [a,b]);

36. What is useCallback?

A: Returns memoized callback, prevents unnecessary re-creations.

const fn = useCallback(() => doSomething(), []);


### 37. What is useRef?
A: Holds mutable value that persists across renders. Often used to access DOM.
```js
const inputRef = useRef();
<input ref={inputRef} />

38. What is React Context?

A: Way to pass data through component tree without props drilling.

39. How to create a Context?

const MyContext = React.createContext();

40. How to use Context Provider?

<MyContext.Provider value={data}>
  <Child />
</MyContext.Provider>

41. How to consume context?

const value = useContext(MyContext);

42. What is React.memo?

A: HOC that memoizes functional components.

export default React.memo(MyComponent);

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?

const OtherComponent = React.lazy(() => import('./OtherComponent'));
<Suspense fallback={<div>Loading...</div>}>
  <OtherComponent />
</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?

fireEvent.click(button);
expect(mockHandler).toHaveBeenCalled();

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?

<BrowserRouter>
 <Routes>
  <Route path="/" element={<Home />} />
  <Route path="/about" element={<About />} />
 </Routes>
</BrowserRouter>

57. How to navigate programmatically?

const navigate = useNavigate();
navigate('/about');

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?

type Props = { title: string };
const Comp: React.FC<Props> = ({ title }) => <h1>{title}</h1>;

66. How to type state with useState?

const [count, setCount] = useState<number>(0);

67. How to type useRef?

const inputRef = useRef<HTMLInputElement>(null);

68. What happens if you update state multiple times in same tick?

setCount(count + 1);
setCount(count + 1);

A: Both run with same count, so only increment once.

69. How to avoid above issue?

setCount(prev => prev + 1);
setCount(prev => prev + 1);

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:

componentDidCatch(error, info) {}
static getDerivedStateFromError(error) { return { hasError: true }; }

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.

useImperativeHandle(ref, () => ({
  focus: () => inputRef.current.focus()
}));

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?

function useCounter() {
  const [count, setCount] = useState(0);
  return [count, () => setCount(count+1)];
}

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?

<img loading="lazy" src="..." alt="..." />

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.

MyComponent.propTypes = {
  name: PropTypes.string.isRequired
};

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:

useEffect(() => {
  async function fetchData() {
    const data = await getData();
    setData(data);
  }
  fetchData();
}, []);

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?

const didMount = useRef(false);
useEffect(() => {
  if (didMount.current) {
    // run after first render
  } else {
    didMount.current = true;
  }
}, [dependency]);

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:

const StateContext = createContext();
export const StateProvider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <StateContext.Provider value={{ state, dispatch }}>
      {children}
    </StateContext.Provider>
  );
};

108. How to memoize context value to prevent re-renders?

const value = useMemo(() => ({ state, dispatch }), [state]);

109. What is forwardRef?

A: Lets you pass ref through a component to a DOM node.

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref}>{props.label}</button>
));
  1. How to expose methods via ref? Use useImperativeHandle:
useImperativeHandle(ref, () => ({
  focus: () => inputRef.current.focus()
}));

111. What is React Query?

A: Powerful library for fetching, caching, synchronizing server state.

112. Example using useQuery?

const { data, isLoading } = useQuery(['todos'], fetchTodos);

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?

import { render, screen } from '@testing-library/react';
render(<MyComponent />);
expect(screen.getByText('Hello')).toBeInTheDocument();

119. How to simulate click with RTL?

fireEvent.click(screen.getByRole('button'));

120. How to use waitFor?

await waitFor(() => expect(screen.getByText('Loaded')).toBeInTheDocument());

121. What is aria-*?

A: Attributes to improve accessibility for assistive tech (screen readers).

122. How to hide visually but keep accessible?

.sr-only {
  position:absolute; width:1px; height:1px; overflow:hidden;
}

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?

<div role="dialog"></div>

Helps assistive tech understand element’s purpose.

126. How to type functional component props?

type Props = { title: string };
const Comp: React.FC<Props> = ({ title }) => <h1>{title}</h1>;

127. How to type state?

const [count, setCount] = useState<number>(0);

128. How to type useReducer?

const [state, dispatch] = useReducer<MyReducerType>(reducer, initialState);

129. How to type ref?

const inputRef = useRef<HTMLInputElement>(null);

130. What is as const?

const theme = { color: 'blue' } as const;

Locks object to literal types.

131. What is Zod?

A: TypeScript-first schema validation library.

132. How to validate object with Zod?

const schema = z.object({ name: z.string() });
schema.parse({ name: "Bob" });

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.

<Accordion>
 <Accordion.Header />
 <Accordion.Body />
</Accordion>

135. What is render props pattern?

A: Pass a function as child to control rendering.

<MyComponent>{(data) => <div>{data}</div>}</MyComponent>

136. What is HOC?

A: Function that takes component and returns enhanced component.

137. Example of simple HOC?

const withLogger = (Component) => (props) => {
  console.log(props);
  return <Component {...props} />;
}

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.

fetchData().then(() => {
  setX(1);
  setY(2);
  // only one re-render
});

153. What is startTransition?

A: Marks UI update as non-urgent, so React can interrupt for higher priority work.

startTransition(() => setSearch(query));

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.

ReactDOM.createPortal(<Modal />, document.getElementById('modal-root'))

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?

useEffect(() => {
  const handler = setTimeout(() => doSearch(query), 300);
  return () => clearTimeout(handler);
}, [query]);

163. How to implement optimistic UI?

A: Immediately update UI, then send API call, rollback if fails.

164. Example of optimistic update?

setTodos(old => [...old, newTodo]);
await api.add(newTodo).catch(() => setTodos(old));

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


### 173. How to mock API with MSW?
A: MSW (Mock Service Worker) intercepts network requests in tests or dev.

### 174. Example mocking fetch?
```js
jest.spyOn(global, 'fetch').mockResolvedValue({ json: () => data });

175. How to test reducer with Jest?

expect(reducer({count:0}, {type:'inc'})).toEqual({count:1});

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?

useEffect(() => {
  const controller = new AbortController();
  fetch(url, { signal: controller.signal });
  return () => controller.abort();
}, [url]);

180. Why wrap API calls inside useEffect?

A: To avoid re-running on every render.

181. How to type generic prop children?

type Props<T> = { items: T[] }
const List = <T,>({items}: Props<T>) => ...

182. How to type forwarded refs?

const Comp = forwardRef<HTMLInputElement, Props>(props, ref) => ...

183. How to type reducer actions?

type Action = { type: 'add'; payload: string }

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?

useForm({ resolver: zodResolver(schema) });

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?

const reducer = (state, action) => ({count: state.count + 1});
const [state, dispatch] = useReducer(reducer, {count: 0});

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?

function useToggle(init = false) {
  const [on, setOn] = useState(init);
  const toggle = () => setOn(o => !o);
  return [on, toggle];
}

195. How to persist state to localStorage?

useEffect(() => {
  localStorage.setItem('key', JSON.stringify(state));
}, [state]);

196. How does key impact reconciliation?

A: Helps React track changes—bad keys cause unnecessary unmount/remount.

197. Why clone element?

React.cloneElement(children, { className: 'extra' })

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.

const [isPending, startTransition] = useTransition();
startTransition(() => setQuery(newQuery));

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?

const queryClient = useQueryClient();
queryClient.invalidateQueries(['todos']);

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?

useQuery(['data'], fetchData, { refetchInterval: 10000 })

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?

const schema = z.object({
  email: z.string().email()
});

214. What is Controller in React Hook Form?

A: Wraps controlled components (like MUI, Antd) to connect with RHF.

<Controller control={control} name="input" render={({ field }) => <Input {...field} />} />

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?

<div className={`${isActive ? 'bg-blue-500' : 'bg-gray-300'}`}></div>

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.

classNames('foo', { 'bar': isActive });

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)?

export async function getStaticProps() {
  return { props: {}, revalidate: 10 }
}

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.

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?

expect(component).toMatchSnapshot();

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?

import dynamic from 'next/dynamic';
const Comp = dynamic(() => import('./Comp'), { ssr: false });

291. Write a hook that toggles boolean on interval.

function useBlink(interval) {
  const [on, setOn] = useState(true);
  useEffect(() => {
    const id = setInterval(() => setOn(o => !o), interval);
    return () => clearInterval(id);
  }, [interval]);
  return on;
}

292. Build pagination with React Query.

Pass page param to queryKey.

useQuery(['users', page], () => fetchUsers(page))

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:

useEffect(() => {
 if (typeof window !== 'undefined') {
   setData(JSON.parse(localStorage.getItem('key')));
 }
}, []);

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.

On this page

1. What is React?2. Who developed React?3. What is JSX?4. Example of JSX?5. Why use keys in lists?6. What is a component?7. Difference between functional and class components?8. What is a prop?9. How to pass data from parent to child?10. Can props change inside a component?11. What is state?12. How to declare state in functional component?13. How to update state in class component?14. Why not modify state directly?15. What is lifecycle in React?16. Example of a lifecycle method?17. What replaces lifecycle methods in functional components?18. What is useEffect?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?23. How to trigger effect on specific variable change?24. How to handle events in React?25. Why onClick not onclick?26. How to handle form input?27. What is controlled vs uncontrolled component?28. How to conditionally render?29. How to render multiple components?30. Why use key in a list?31. What is a hook?32. Name some built-in hooks.33. What is useContext?34. What is useReducer?35. What is useMemo?36. What is useCallback?38. What is React Context?39. How to create a Context?40. How to use Context Provider?41. How to consume context?42. What is React.memo?43. What is shouldComponentUpdate?44. What is React.lazy?45. Example of React.lazy with Suspense?46. What is Jest?47. What is React Testing Library?48. How to test a click event?49. Why is React called declarative?### 50. What is virtual DOM?51. What is hydration?52. What is reconciliation?53. What is prop drilling?54. How to solve prop drilling?55. What is React Router?56. Basic routing example?57. How to navigate programmatically?58. What is Redux?59. What is store in Redux?60. What are actions in Redux?61. What is a reducer?62. What is middleware in Redux?63. What is connect?64. What are useSelector & useDispatch?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?69. How to avoid above issue?70. What are controlled vs uncontrolled inputs?71. What is dangerouslySetInnerHTML?72. What happens if you forget key in a list?73. Can you use multiple useEffect?74. Can hooks be inside loops or conditions?75. What is StrictMode?76. Why avoid using index as key?77. What is an error boundary?78. How to create an error boundary?79. Can hooks catch errors?80. What is useLayoutEffect?81. When to prefer useLayoutEffect?82. What is useImperativeHandle?83. What is a custom hook?84. Example of a custom hook?85. What is Suspense?86. Can Suspense handle data fetching today?87. What is concurrent rendering?88. What is SSR in React?89. What is hydration?90. How does Next.js help with React SSR?91. What is getStaticProps?92. What is getServerSideProps?93. What is API Routes in Next.js?94. What is tree shaking in React apps?95. What does webpack do?96. What is code splitting?97. What is React.StrictMode used for?98. How to lazy load image?99. What is Helmet in React?100. What is PropTypes?101. Can you use hooks inside conditions or loops?102. How to handle async in useEffect?103. What happens if you omit dependencies in useEffect?104. How to skip effect on first render?105. Why might you see “Too many re-renders” error?106. When to use useReducer over useState?107. How to combine useReducer with Context?108. How to memoize context value to prevent re-renders?109. What is forwardRef?111. What is React Query?112. Example using useQuery?113. How does React Query differ from Redux?114. What is stale time vs cache time?115. Can React Query work with Suspense?116. What is React Testing Library (RTL)?117. What is the philosophy of RTL?118. Example of RTL rendering a component?119. How to simulate click with RTL?120. How to use waitFor?121. What is aria-*?122. How to hide visually but keep accessible?123. Why prefer button over clickable div?124. How to ensure focus order?125. What is role attribute for?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?131. What is Zod?132. How to validate object with Zod?133. How to integrate with React forms?134. What is compound component pattern?135. What is render props pattern?136. What is HOC?137. Example of simple HOC?138. Difference HOC vs custom hook?139. What is a controlled vs uncontrolled component?140. What is slots pattern?141. Why is virtual DOM faster?142. How does reconciliation algorithm work?143. What is hydration mismatch warning?144. What are React fibers?145. Why do stale closures happen?146. What is ESLint plugin for React?147. What is Prettier used for?148. How to prevent unnecessary re-renders?149. What is Suspense fallback for?150. What is code splitting?151. What’s new in React 18?152. What is automatic batching?153. What is startTransition?154. What is useDeferredValue?155. What is useId?156. What is a React Portal?157. When use portals?158. What is React DevTools profiler?159. How to find unnecessary renders?160. Why enable React StrictMode?161. How to build infinite scroll?162. How to debounce input in React?163. How to implement optimistic UI?164. Example of optimistic update?165. What is skeleton loading?166. How does Zustand compare to Redux?167. How does Recoil work?168. What is Jotai?169. How to deploy React on Netlify?170. How about Vercel?171. Why set homepage in package.json?172. How to avoid 404 on refresh in SPA?175. How to test reducer with Jest?176. What is Cypress?177. What is error fallback UI?178. How to handle stale props in async?179. Example of AbortController in React?180. Why wrap API calls inside useEffect?181. How to type generic prop children?182. How to type forwarded refs?183. How to type reducer actions?184. What is Formik?185. What is React Hook Form?186. How to integrate Zod + React Hook Form?187. Difference between controlled & uncontrolled form in RHF?188. What is ISR in Next.js?189. What is SSG vs SSR vs CSR?190. How to protect SSR pages?191. Build a counter with useReducer?192. How to debounce input with hooks?193. How to throttle scroll?194. Build custom hook useToggle?195. How to persist state to localStorage?196. How does key impact reconciliation?197. Why clone element?198. What is dangerouslySetInnerHTML?199. What is hydration mismatch?200. Why is React declarative?201. What is useTransition?202. Difference useTransition vs startTransition?203. What is concurrent mode?204. What is React Server Components (RSC)?205. Does Suspense for data fetching work natively?206. How does SWR differ from React Query?207. What is stale-while-revalidate?208. How to refetch manually in React Query?209. What does onSuccess vs onSettled mean?210. How to poll with React Query?211. What is Yup?212. Difference Zod vs Yup?213. How to validate email with Zod?214. What is Controller in React Hook Form?215. What is setValue in RHF?216. What is Tailwind CSS?217. How to integrate Tailwind with CRA?218. How to conditionally add Tailwind classes?219. What is Headless UI?220. How does classnames library help?221. How does Next.js routing work?222. What is API Route?223. What is middleware in Next.js?224. How to enable ISR (Incremental Static Regeneration)?225. How to fetch user data on server in Next.js?226. What is XState?227. Advantage of state machines over useState?228. How to integrate XState with React?229. Can XState work with Next.js?230. What is lazy hydration?231. How to defer hydration in Next.js?232. What is prefetch in Next.js?233. What is code splitting by component?234. Why measure bundle size?235. What is long task blocking?236. Why use semantic tags (<button>, <nav>, etc)?237. What is skip link?238. How to make modal accessible?239. Why use aria-live?240. How to audit a11y?241. How to persist auth token in React?242. How to cancel API call on unmount?243. How to combine refs?244. What is prop getter pattern?245. What is compound components pattern?246. What is React DevTools highlight updates?247. What is Storybook?248. How to automate tests in CI?249. How to deploy Next.js on Vercel?250. What is .env.local?251. What is getInitialProps?252. Difference getStaticProps vs getServerSideProps vs getInitialProps?253. What is Next.js Middleware?254. What is Edge Runtime in Next.js?255. What is Streaming SSR (React 18)?256. How to handle i18n in Next.js?257. How to manage translations in React?258. What is a namespace in i18next?259. What is guards in XState?260. What are invoked services in XState?261. Why use state machines for forms?262. What is micro-frontend architecture?263. How to share state between micro-frontends?264. What is multi-tenant app?265. What is Radix UI?266. How does Chakra UI differ?267. What is styled-system?268. What is Emotion vs Styled Components?269. How to animate in React?270. How to build dark mode toggle?271. What is queryKey in React Query?272. What does keepPreviousData do?273. What is select option in useQuery?274. How does SWR handle caching?275. How to persist React Query cache across reloads?276. How to test custom hooks?277. How to mock React Router?278. How to snapshot test with Jest?279. Why prefer user-event over fireEvent?280. How to measure test coverage?281. What is preview deployment?282. How to optimize build times?283. What does next build do?284. Why `NODE_ENV=production matters?285. What is SWC in Next.js?286. How to avoid prop drilling without context?287. How to prevent layout shift?288. What is hydration mismatch error?289. How to track performance in React?290. How to lazy load component only on client?291. Write a hook that toggles boolean on interval.292. Build pagination with React Query.293. Build modal with escape to close.294. How to persist state with localStorage + SSR safe?295. How to debounce search input?296. How to skip hydration of client-only widget?297. What’s the biggest React perf anti-pattern?298. When to memoize component with React.memo?299. How to visualize re-renders?300. What excites you most about React’s future?