[{"data":1,"prerenderedAt":513},["ShallowReactive",2],{"all-questions-react":3},{"beginner":4,"intermediate":208,"advanced":357},[5,15,22,31,39,48,56,64,72,82,91,97,107,116,121,131,138,144,150,158,166,173,183,190,199],{"id":6,"category":7,"question":8,"answer":9,"level":10,"tags":11},1,"Basics","What is React? Explain its core concepts and how it differs from traditional DOM manipulation.","**Concept Explanation:**\nReact is a JavaScript library for building user interfaces, developed by Meta. It uses a declarative paradigm where you describe what the UI should look like for a given state, and React efficiently updates and renders the right components when data changes. Unlike traditional imperative DOM manipulation (e.g., `document.getElementById` and `innerHTML`), React uses a virtual DOM to minimize direct browser API calls.\n\n**Syntax Explanation:**\n```jsx\n\u002F\u002F Declarative React component\nfunction Greeting({ name }) {\n  return \u003Ch1>Hello, {name}!\u003C\u002Fh1>;\n}\n\n\u002F\u002F Traditional imperative approach\nfunction updateGreeting(name) {\n  const el = document.getElementById('greeting');\n  el.innerHTML = `Hello, ${name}!`;\n}\n```\n\n**Code Example:**\n```jsx\nimport React, { useState } from 'react';\n\nfunction Counter() {\n  const [count, setCount] = useState(0);\n  return (\n    \u003Cbutton onClick={() => setCount(count + 1)}>\n      Clicked {count} times\n    \u003C\u002Fbutton>\n  );\n}\n```\n\n**Execution Flow:**\n1. React creates a virtual DOM tree representing the UI.\n2. When state changes, React creates a new virtual DOM tree.\n3. React diffs the old and new virtual trees (reconciliation).\n4. React computes the minimal set of changes needed and applies them to the real DOM.\n\n**Reactivity Explanation:**\nReact's reactivity is driven by state changes. When `setState` (or useState setter) is called, React schedules a re-render of the component and its children, then performs reconciliation.\n\n**Practical Usage:**\n- Building single-page applications (SPAs).\n- Creating component-based UIs for web and mobile (React Native).\n- Server-rendered applications (Next.js).\n\n**Common Mistakes:**\n- Directly mutating state instead of using setter functions.\n- Calling hooks conditionally or outside functional components.\n- Not providing unique `key` props in lists.\n\n**Interview Follow-ups:**\n- What is the virtual DOM and how does it work?\n- What is the difference between React and ReactDOM?\n- How does React handle updates efficiently?\n\n**Best Practices:**\n- Keep components small and focused.\n- Use functional components with hooks.\n- Name event handlers with `handle` prefix (e.g., `handleClick`).\n- Use `key` prop in lists with stable, unique identifiers.\n\n**Performance Considerations:**\n- Virtual DOM diffing is generally fast, but large lists with unstable keys can cause performance issues.\n- Use `React.memo` to prevent unnecessary re-renders.\n\n**Production Recommendations:**\n- Use production build (minified, optimized).\n- Enable React DevTools for debugging.\n- Use code splitting with `React.lazy` and Suspense.\n\n**Node.js \u002F SSR Behavior:**\nReact can be rendered on the server using `renderToString` (Next.js, Remix). The same component code runs in Node.js environment; lifecycle methods like `useEffect` do not run during SSR.\n\n**Latest React Patterns:**\n- Functional components with hooks are the standard (class components are legacy).\n- Use `useState` and `useEffect` for side effects.\n\n**TypeScript Example:**\n```tsx\ninterface GreetingProps {\n  name: string;\n}\n\nconst Greeting: React.FC\u003CGreetingProps> = ({ name }) => {\n  return \u003Ch1>Hello, {name}!\u003C\u002Fh1>;\n};\n```\n\n**Interview Tip:**\nStart by contrasting declarative vs imperative. Emphasize that React manages DOM updates for you, making code more predictable and easier to maintain.\n\n**Common Follow-up:**\n\"How does React's virtual DOM improve performance compared to directly manipulating the DOM?\"\n\n**Real-world Example:**\nA dashboard that refreshes data every second – with React, you only update the state, and React handles re-rendering only the changed parts.\n\n**Advanced Notes:**\nReact uses a Fiber architecture to enable interruptible rendering. The virtual DOM is not a direct performance win over well-written manual DOM updates, but it provides a declarative model that scales well.","beginner",[12,13,14],"basics","virtual-dom","react-intro",{"id":16,"category":7,"question":17,"answer":18,"level":10,"tags":19},2,"What is JSX? How does it differ from HTML and what are its rules?","**Concept Explanation:**\nJSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like markup inside JavaScript files. It gets compiled by tools like Babel into `React.createElement` calls. JSX is not a template language; it uses the full power of JavaScript.\n\n**Syntax Explanation:**\n```jsx\n\u002F\u002F JSX syntax\nconst element = \u003Ch1 className=\"title\">Hello, {name}\u003C\u002Fh1>;\n\n\u002F\u002F Compiled output\nconst element = React.createElement('h1', { className: 'title' }, 'Hello, ', name);\n```\n\n**Code Example:**\n```jsx\nfunction Welcome({ user }) {\n  return (\n    \u003Cdiv>\n      \u003Ch1>Welcome {user.name}\u003C\u002Fh1>\n      {user.isAdmin && \u003Cbutton>Admin Panel\u003C\u002Fbutton>}\n      \u003Cul>\n        {user.items.map(item => \u003Cli key={item.id}>{item.name}\u003C\u002Fli>)}\n      \u003C\u002Ful>\n    \u003C\u002Fdiv>\n  );\n}\n```\n\n**Execution Flow:**\n1. Babel (or other compiler) parses JSX.\n2. Transforms JSX tags into `React.createElement` calls.\n3. React runtime creates virtual DOM elements.\n4. ReactDOM renders to actual DOM.\n\n**Reactivity Explanation:**\nJSX expressions `{ }` can embed JavaScript values; when those values (state\u002Fprops) change, React re-evaluates the JSX and updates the DOM.\n\n**Practical Usage:**\n- Defining component structures declaratively.\n- Embedding JavaScript logic directly in markup.\n- Composing components together.\n\n**Common Mistakes:**\n- Using `class` instead of `className`.\n- Forgetting curly braces for JavaScript expressions.\n- Using `\u003C!-- comment -->` instead of `{\u002F* comment *\u002F}`.\n- Returning multiple adjacent elements without a wrapper fragment `\u003C>\u003C\u002F>`.\n\n**Interview Follow-ups:**\n- Why can't browsers understand JSX directly?\n- What is the purpose of `React` being in scope when using JSX (pre React 17)?\n- What is the difference between JSX and HTML?\n\n**Best Practices:**\n- Use parentheses `()` for multi-line JSX to avoid automatic semicolon insertion issues.\n- Keep expressions simple; extract complex logic outside return.\n- Use fragments `\u003C>...\u003C\u002F>` to avoid extra DOM nodes.\n\n**Performance Considerations:**\n- JSX itself adds no runtime overhead because it compiles to plain JavaScript calls.\n- The `key` prop in lists helps React identify items for efficient updates.\n\n**Production Recommendations:**\n- Use `eslint-plugin-react` to enforce JSX rules.\n- Enable JSX transform (React 17+).\n\n**Node.js \u002F SSR Behavior:**\nJSX compiles to `React.createElement`, which works in Node.js environment for server-side rendering.\n\n**Latest React Patterns:**\n- New JSX transform (React 17+) allows you to omit `import React from 'react'`.\n- Using fragments (`\u003C>\u003C\u002F>`) is common.\n\n**TypeScript Example:**\n```tsx\ninterface Props {\n  name: string;\n}\n\nconst Greeting: React.FC\u003CProps> = ({ name }) => {\n  return \u003Cdiv className=\"greeting\">Hello {name}!\u003C\u002Fdiv>;\n};\n```\n\n**Interview Tip:**\nExplain that JSX is syntactic sugar for `React.createElement`. Emphasize that expressions in `{}` can be any JavaScript expression (function calls, ternary operators, variables).\n\n**Common Follow-up:**\n\"Can you use JavaScript statements like `if` inside JSX? How would you conditionally render?\"\n\n**Real-world Example:**\nRendering a list of products with conditional stock status:\n```jsx\n\u003Cdiv>\n  {products.map(product => (\n    \u003Cdiv key={product.id}>\n      {product.name} - {product.inStock ? 'In stock' : 'Out of stock'}\n    \u003C\u002Fdiv>\n  ))}\n\u003C\u002Fdiv>\n```\n\n**Advanced Notes:**\nJSX allows custom components to be treated as elements: `\u003CMyComponent \u002F>`. The transformation relies on the `jsx` function in React 17+, which can be customized for different libraries (Preact, Inferno).",[20,21,12],"jsx","syntax",{"id":23,"category":24,"question":25,"answer":26,"level":10,"tags":27},3,"Components","What are functional components in React? How do they differ from class components?","**Concept Explanation:**\nFunctional components are JavaScript functions that accept props as an argument and return React elements (JSX). They are simpler, lighter, and the recommended way to write components since React 16.8 introduced hooks. Class components extend `React.Component` and use `render` method, `this.state`, and lifecycle methods.\n\n**Syntax Explanation:**\n```jsx\n\u002F\u002F Functional component\nfunction Welcome({ name }) {\n  return \u003Ch1>Hello, {name}\u003C\u002Fh1>;\n}\n\n\u002F\u002F Arrow function variant\nconst Welcome = ({ name }) => \u003Ch1>Hello, {name}\u003C\u002Fh1>;\n\n\u002F\u002F Class component\nclass WelcomeClass extends React.Component {\n  render() {\n    return \u003Ch1>Hello, {this.props.name}\u003C\u002Fh1>;\n  }\n}\n```\n\n**Code Example with State:**\n```jsx\n\u002F\u002F Functional with hooks\nimport { useState } from 'react';\n\nfunction Counter() {\n  const [count, setCount] = useState(0);\n  return \u003Cbutton onClick={() => setCount(count + 1)}>Count: {count}\u003C\u002Fbutton>;\n}\n\n\u002F\u002F Class with state\nclass CounterClass extends React.Component {\n  state = { count: 0 };\n  render() {\n    return \u003Cbutton onClick={() => this.setState({ count: this.state.count + 1 })}>\n      Count: {this.state.count}\n    \u003C\u002Fbutton>;\n  }\n}\n```\n\n**Execution Flow:**\nFunctional components are invoked directly; their returned JSX is converted to virtual DOM. Class components are instantiated, `render` called. Hooks in functional components rely on a call order system.\n\n**Reactivity Explanation:**\nIn functional components, `useState` returns a state variable and a setter. When the setter is called, React re-runs the entire function component to compute the new UI. In class components, `setState` merges state and triggers `render`.\n\n**Practical Usage:**\n- All new components should be functional.\n- Use class components only when necessary (legacy codebases, error boundaries before React 16.8? Actually error boundaries still require classes).\n\n**Common Mistakes:**\n- Forgetting to import `useState`\u002F`useEffect` in functional components.\n- Calling hooks conditionally.\n- In class components, forgetting to bind event handlers or using `this` incorrectly.\n\n**Interview Follow-ups:**\n- What are hooks and why were they introduced?\n- Can you use lifecycle methods in functional components? (Yes, via `useEffect`)\n- When would you still use a class component? (Error boundaries, legacy code)\n\n**Best Practices:**\n- Always use functional components with hooks.\n- Name functional components with PascalCase.\n- Keep components pure (no side effects in render).\n\n**Performance Considerations:**\n- Functional components have less overhead (no instance, no `this` binding).\n- React.memo can be used with functional components to prevent re-renders.\n\n**Production Recommendations:**\n- Use `React.memo` for expensive functional components.\n- Use `useCallback` and `useMemo` to optimize child component rendering.\n\n**Node.js \u002F SSR Behavior:**\nBoth component types can be SSR'd. Lifecycle methods like `componentDidMount` do not run on server; `useEffect` also doesn't run on server.\n\n**Latest React Patterns:**\n- Functional components with hooks are the standard.\n- React Server Components are also functional but async (no hooks).\n\n**TypeScript Example:**\n```tsx\ninterface ButtonProps {\n  onClick: () => void;\n  children: React.ReactNode;\n}\n\nconst Button: React.FC\u003CButtonProps> = ({ onClick, children }) => (\n  \u003Cbutton onClick={onClick}>{children}\u003C\u002Fbutton>\n);\n```\n\n**Interview Tip:**\nHighlight that functional components are just functions – simpler to test, less boilerplate. Hooks allow state and side effects without classes.\n\n**Common Follow-up:**\n\"How do you implement `componentDidMount` in a functional component?\" (useEffect with empty dependency array)\n\n**Real-world Example:**\nA typical modern React app consists entirely of functional components, using `useState`, `useEffect`, custom hooks, and `useContext` for state management.\n\n**Advanced Notes:**\nClass components have a different `this` context; React automatically binds methods that are passed as JSX props? No, you need to bind or use arrow functions. Functional components capture the current props and state in closures, avoiding stale closure issues when using `useCallback` with dependencies.",[28,29,30,12],"components","functional","class",{"id":32,"category":24,"question":33,"answer":34,"level":10,"tags":35},4,"How do you pass data between components using props? Explain prop drilling and basic parent-child communication.","**Concept Explanation:**\nProps (properties) are read-only data passed from a parent component to child components. Props flow uni-directionally (parent to child). To communicate child to parent, you pass a callback function as a prop that the child calls with data. Prop drilling occurs when you need to pass props through many intermediate components that don't need the data.\n\n**Syntax Explanation:**\n```jsx\n\u002F\u002F Parent passes props\nfunction Parent() {\n  const [message, setMessage] = useState('Hello');\n  return \u003CChild text={message} onUpdate={setMessage} \u002F>;\n}\n\n\u002F\u002F Child receives props\nfunction Child({ text, onUpdate }) {\n  return \u003Cbutton onClick={() => onUpdate('Updated')}>{text}\u003C\u002Fbutton>;\n}\n```\n\n**Code Example:**\n```jsx\n\u002F\u002F Parent to child\nfunction UserCard({ user }) {\n  return \u003Cdiv>{user.name}\u003C\u002Fdiv>;\n}\n\nfunction App() {\n  const user = { name: 'Alice', age: 25 };\n  return \u003CUserCard user={user} \u002F>;\n}\n\n\u002F\u002F Child to parent via callback\nfunction TodoList() {\n  const [todos, setTodos] = useState([]);\n  const addTodo = (text) => setTodos([...todos, text]);\n  return \u003CTodoInput onAdd={addTodo} \u002F>;\n}\n\nfunction TodoInput({ onAdd }) {\n  const [value, setValue] = useState('');\n  return (\n    \u003C>\n      \u003Cinput value={value} onChange={e => setValue(e.target.value)} \u002F>\n      \u003Cbutton onClick={() => onAdd(value)}>Add\u003C\u002Fbutton>\n    \u003C\u002F>\n  );\n}\n```\n\n**Execution Flow:**\n1. Parent renders, creates JSX with child component and prop values.\n2. React passes props to child component as a JavaScript object.\n3. Child component receives props as argument (functional) or `this.props` (class).\n4. When parent state changes, React re-renders parent, passes new props to child.\n5. Child may re-render if props changed (or by default).\n\n**Reactivity Explanation:**\nProps are reactive: when a parent's state changes, new prop values are passed down, causing child to re-render (unless memoized).\n\n**Practical Usage:**\n- Passing configuration data to child components.\n- Sharing event handlers from parent to child.\n- Rendering dynamic content based on props.\n\n**Common Mistakes:**\n- Trying to mutate props directly (props are immutable).\n- Prop drilling (passing props through many levels) making code hard to maintain.\n- Forgetting to pass required props.\n\n**Interview Follow-ups:**\n- How do you avoid prop drilling? (Context API, component composition, state management libraries)\n- What is the difference between props and state?\n- Can a child component modify parent state? (Only via callback props)\n\n**Best Practices:**\n- Use destructuring to extract props.\n- Provide default values for optional props (`function MyComponent({ name = 'Guest' })`).\n- Use PropTypes or TypeScript for type checking.\n\n**Performance Considerations:**\n- Passing new object\u002Ffunction references on every render can cause unnecessary child re-renders. Use `useCallback` and `useMemo`.\n- Prop drilling can cause intermediate components to re-render unnecessarily (React.memo can help).\n\n**Production Recommendations:**\n- For deep prop passing, consider Context API or state management (Zustand, Redux).\n- Use TypeScript to enforce prop types.\n\n**Node.js \u002F SSR Behavior:**\nProps are serialized during SSR. Functions as props are not serialized and will be omitted on the server.\n\n**Latest React Patterns:**\n- Composition over prop drilling: pass components as children or render props.\n- Context API for global state.\n\n**TypeScript Example:**\n```tsx\ninterface ChildProps {\n  text: string;\n  onUpdate: (newText: string) => void;\n}\n\nconst Child: React.FC\u003CChildProps> = ({ text, onUpdate }) => {\n  return \u003Cbutton onClick={() => onUpdate('new')}>{text}\u003C\u002Fbutton>;\n};\n```\n\n**Interview Tip:**\nEmphasize the unidirectional data flow (parent to child via props, child to parent via callbacks). Mention that props are read-only; state is internal and mutable.\n\n**Common Follow-up:**\n\"What is prop drilling and why is it problematic? How would you solve it?\"\n\n**Real-world Example:**\nA dashboard component with deeply nested widgets: instead of passing user permissions down every level, use Context API or a state management library.\n\n**Advanced Notes:**\nReact's `cloneElement` can be used to inject props into children, but it's rarely needed. Render props pattern (passing a function as a child) is an alternative for sharing logic but largely replaced by hooks.",[36,37,38],"props","data-flow","communication",{"id":40,"category":41,"question":42,"answer":43,"level":10,"tags":44},5,"State Management","What is state in React? Explain the useState hook with examples and rules of hooks.","**Concept Explanation:**\nState is data that changes over time within a component and causes re-renders when updated. `useState` is a React hook that adds state to functional components. It returns an array with two elements: the current state value and a setter function to update it.\n\n**Syntax Explanation:**\n```jsx\nimport { useState } from 'react';\n\nconst [count, setCount] = useState(0);   \u002F\u002F initial value 0\nconst [name, setName] = useState('');    \u002F\u002F string\nconst [user, setUser] = useState(null);  \u002F\u002F any type\n```\n\n**Code Example:**\n```jsx\nfunction Counter() {\n  const [count, setCount] = useState(0);\n\n  const increment = () => setCount(count + 1);\n  const decrement = () => setCount(prev => prev - 1); \u002F\u002F functional update\n\n  return (\n    \u003Cdiv>\n      \u003Cp>Count: {count}\u003C\u002Fp>\n      \u003Cbutton onClick={increment}>+\u003C\u002Fbutton>\n      \u003Cbutton onClick={decrement}>-\u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  );\n}\n\n\u002F\u002F Multiple states\nfunction Form() {\n  const [email, setEmail] = useState('');\n  const [password, setPassword] = useState('');\n\n  const handleSubmit = (e) => {\n    e.preventDefault();\n    console.log({ email, password });\n  };\n\n  return (\n    \u003Cform onSubmit={handleSubmit}>\n      \u003Cinput value={email} onChange={e => setEmail(e.target.value)} \u002F>\n      \u003Cinput value={password} onChange={e => setPassword(e.target.value)} \u002F>\n    \u003C\u002Fform>\n  );\n}\n```\n\n**Execution Flow:**\n1. React calls the component function.\n2. `useState` checks the hook index (based on call order).\n3. If first render, initializes state and stores it in Fiber node.\n4. Returns current state and setter.\n5. When setter is called, React schedules a re-render.\n6. On re-render, `useState` returns the updated state (same index).\n\n**Reactivity Explanation:**\nState changes trigger re-renders. React batches state updates in event handlers for performance. Using functional update `setCount(prev => prev + 1)` ensures you always get the latest previous value, important for async updates or multiple updates in a row.\n\n**Practical Usage:**\n- Tracking user input in forms.\n- Toggling UI elements (modals, dropdowns).\n- Storing fetched data.\n- Managing component-specific UI state.\n\n**Common Mistakes:**\n- Mutating state directly: `count = 5` instead of `setCount(5)`.\n- Calling hooks conditionally or in loops.\n- Using state setter with same value that doesn't trigger re-render (object references).\n- Forgetting that state updates may be asynchronous.\n\n**Interview Follow-ups:**\n- What are the rules of hooks and why do they exist?\n- How does React know which state corresponds to which `useState` call?\n- What is the difference between `setCount(count + 1)` and `setCount(prev => prev + 1)`?\n\n**Best Practices:**\n- Use multiple `useState` calls for unrelated state variables.\n- Use functional updates when new state depends on previous state.\n- Name state variables descriptively: `[isLoading, setIsLoading]`.\n\n**Performance Considerations:**\n- State updates cause re-renders of the component and its children. Use `React.memo` to prevent unnecessary child re-renders.\n- Avoid storing derived data in state (compute during render instead).\n\n**Production Recommendations:**\n- Use state management libraries (Zustand, Redux, Context) for global state.\n- Use `useReducer` for complex state logic.\n\n**Node.js \u002F SSR Behavior:**\n`useState` does not run during SSR because there is no re-rendering. Initial state values are used for the initial HTML output.\n\n**Latest React Patterns:**\n- `useState` can be lazy-initialized with a function: `useState(() => expensiveComputation())`.\n- State updater functions are stable (same identity across renders).\n\n**TypeScript Example:**\n```tsx\ninterface User {\n  name: string;\n  age: number;\n}\n\nconst [user, setUser] = useState\u003CUser | null>(null);\nconst [count, setCount] = useState\u003Cnumber>(0);\n```\n\n**Interview Tip:**\nExplain that hooks rely on call order; that's why you can't put them inside conditions. Mention the \"Rules of Hooks\" – only call hooks at the top level and only from React functions.\n\n**Common Follow-up:**\n\"How do you update state based on previous state?\"\n\n**Real-world Example:**\nShopping cart quantity update: `setQuantity(prev => prev + 1)` inside an async callback ensures you increment correctly even if multiple updates are batched.\n\n**Advanced Notes:**\nReact internally uses a linked list of hooks attached to the fiber node. The order determines which hook gets which state. The setter function from `useState` never changes, so it can be omitted from `useEffect` dependencies safely.",[45,46,47,12],"state","useState","hooks",{"id":49,"category":7,"question":50,"answer":51,"level":10,"tags":52},6,"How do you handle events in React? Explain synthetic events and common event handlers.","**Concept Explanation:**\nReact events are named using camelCase (`onClick` instead of `onclick`). You pass a function as the event handler, not a string. React wraps native DOM events in a `SyntheticEvent` wrapper that normalizes events across browsers. Synthetic events are pooled for performance (in older React versions) – but modern React no longer uses pooling.\n\n**Syntax Explanation:**\n```jsx\nfunction Button() {\n  const handleClick = (event) => {\n    console.log('Clicked!', event);\n  };\n\n  return \u003Cbutton onClick={handleClick}>Click me\u003C\u002Fbutton>;\n}\n```\n\n**Code Example:**\n```jsx\nfunction EventDemo() {\n  const [value, setValue] = useState('');\n\n  const handleChange = (e) => setValue(e.target.value);\n  const handleSubmit = (e) => {\n    e.preventDefault();\n    alert(`Submitted: ${value}`);\n  };\n  const handleMouseEnter = () => console.log('Mouse entered');\n  const handleKeyDown = (e) => {\n    if (e.key === 'Enter') console.log('Enter pressed');\n  };\n\n  return (\n    \u003Cform onSubmit={handleSubmit}>\n      \u003Cinput\n        value={value}\n        onChange={handleChange}\n        onKeyDown={handleKeyDown}\n      \u002F>\n      \u003Cbutton type=\"submit\" onMouseEnter={handleMouseEnter}>Submit\u003C\u002Fbutton>\n    \u003C\u002Fform>\n  );\n}\n```\n\n**Execution Flow:**\n1. User interacts with DOM element.\n2. Browser fires native event.\n3. React's event system captures the event at the root level (event delegation).\n4. React creates a `SyntheticEvent` wrapper.\n5. React calls the JSX-attached handler with the synthetic event.\n6. After handler runs, synthetic event is recycled (historically) – but no longer in React 17+.\n\n**Reactivity Explanation:**\nEvent handlers can call state setters, triggering re-renders. They can also call `preventDefault` and `stopPropagation` just like native events.\n\n**Practical Usage:**\n- Form submission (`onSubmit`).\n- Button clicks (`onClick`).\n- Input changes (`onChange`).\n- Keyboard shortcuts (`onKeyDown`).\n\n**Common Mistakes:**\n- Calling the function instead of passing it: `onClick={handleClick()}` (executes on render).\n- Forgetting to bind methods in class components.\n- Using `onChange` but not updating state (making input read-only).\n\n**Interview Follow-ups:**\n- What is a synthetic event? Why does React use them?\n- How does event delegation work in React?\n- What is the difference between `onChange` and `onInput` in React?\n\n**Best Practices:**\n- Name event handlers starting with `handle`: `handleClick`, `handleSubmit`.\n- Use arrow functions or `useCallback` to avoid unnecessary re-renders when passing handlers to child components.\n- Call `e.preventDefault()` early in the handler to avoid unexpected behavior.\n\n**Performance Considerations:**\n- Inline arrow functions in JSX create new function instances on each render. For child components that are memoized, this can break memoization. Use `useCallback` to stabilize handler references.\n- React attaches a single event listener per event type to the root container (event delegation) which is efficient.\n\n**Production Recommendations:**\n- Use `react-query` or similar for data-fetching events (form submission).\n- For complex event handling (drag-and-drop), consider libraries like `react-use`.\n\n**Node.js \u002F SSR Behavior:**\nEvent handlers don't run during SSR because there are no user interactions. The JSX event props are still passed but ignored.\n\n**Latest React Patterns:**\n- React 17 changed event delegation to attach to the root DOM container instead of document.\n- `onChange` in React behaves like `onInput` in native DOM (fires on every keystroke).\n\n**TypeScript Example:**\n```tsx\nconst handleChange = (e: React.ChangeEvent\u003CHTMLInputElement>) => {\n  setValue(e.target.value);\n};\n\nconst handleSubmit = (e: React.FormEvent\u003CHTMLFormElement>) => {\n  e.preventDefault();\n};\n```\n\n**Interview Tip:**\nExplain that synthetic events provide cross-browser consistency. Mention that React 17+ removed event pooling, so you can access event asynchronously (e.g., in `setTimeout`).\n\n**Common Follow-up:**\n\"How do you pass additional parameters to an event handler?\" (Wrap in arrow function: `onClick={() => handleClick(id)}`)\n\n**Real-world Example:**\nSearch input that triggers search on every keystroke:\n```jsx\n\u003Cinput onChange={e => setSearchTerm(e.target.value)} \u002F>\n```\n\n**Advanced Notes:**\nReact's event system supports custom events and can integrate with third-party libraries. `SyntheticEvent` implements the same interface as native DOM events but without browser-specific quirks. In React 17+, `e.persist()` is no longer needed.",[53,54,55],"events","synthetic-events","handlers",{"id":57,"category":58,"question":59,"answer":60,"level":10,"tags":61},7,"Rendering","How does conditional rendering work in React? Show different methods with examples.","**Concept Explanation:**\nConditional rendering in React works the same way conditions work in JavaScript. You can use `if` statements, ternary operators, logical AND (`&&`), or switch statements to decide which JSX to render. React will only render the branch that evaluates to true.\n\n**Syntax Explanation:**\n```jsx\nfunction Greeting({ isLoggedIn }) {\n  \u002F\u002F 1. if\u002Felse\n  if (isLoggedIn) {\n    return \u003Ch1>Welcome back!\u003C\u002Fh1>;\n  } else {\n    return \u003Ch1>Please sign in.\u003C\u002Fh1>;\n  }\n}\n\n\u002F\u002F 2. Ternary operator\nfunction Greeting({ isLoggedIn }) {\n  return (\n    \u003Cdiv>\n      {isLoggedIn ? \u003Ch1>Welcome back!\u003C\u002Fh1> : \u003Ch1>Please sign in.\u003C\u002Fh1>}\n    \u003C\u002Fdiv>\n  );\n}\n\n\u002F\u002F 3. Logical AND (&&)\nfunction Notification({ count }) {\n  return (\n    \u003Cdiv>\n      {count > 0 && \u003Cspan>You have {count} new messages\u003C\u002Fspan>}\n    \u003C\u002Fdiv>\n  );\n}\n\n\u002F\u002F 4. Variable assignment\nfunction Greeting({ isLoggedIn, user }) {\n  let message;\n  if (isLoggedIn) {\n    message = \u003Ch1>Welcome {user.name}!\u003C\u002Fh1>;\n  } else {\n    message = \u003Ch1>Please log in\u003C\u002Fh1>;\n  }\n  return \u003Cdiv>{message}\u003C\u002Fdiv>;\n}\n```\n\n**Code Example:**\n```jsx\nfunction UserProfile({ user, loading, error }) {\n  if (loading) return \u003Cdiv>Loading...\u003C\u002Fdiv>;\n  if (error) return \u003Cdiv>Error: {error.message}\u003C\u002Fdiv>;\n  if (!user) return \u003Cdiv>No user data\u003C\u002Fdiv>;\n\n  return (\n    \u003Cdiv>\n      \u003Ch2>{user.name}\u003C\u002Fh2>\n      \u003Cp>Email: {user.email}\u003C\u002Fp>\n    \u003C\u002Fdiv>\n  );\n}\n\n\u002F\u002F Multiple conditions\nfunction RoleBasedContent({ role }) {\n  return (\n    \u003Cdiv>\n      {role === 'admin' && \u003CAdminPanel \u002F>}\n      {role === 'editor' && \u003CEditorPanel \u002F>}\n      {role === 'viewer' && \u003CViewerPanel \u002F>}\n      {!role && \u003CLoginPrompt \u002F>}\n    \u003C\u002Fdiv>\n  );\n}\n```\n\n**Execution Flow:**\nReact evaluates the conditional expression during the render phase. If the condition returns `false`, `null`, `undefined`, or `false` expression, nothing is rendered for that part. For `&&`, if the left side is falsy, React skips the right side.\n\n**Reactivity Explanation:**\nConditional rendering is recalculated on every render. When the condition depends on state\u002Fprops, changes trigger re-evaluation and DOM updates.\n\n**Practical Usage:**\n- Show loading spinners while fetching data.\n- Display error messages.\n- Toggle modals\u002Fdropdowns.\n- Role-based access control.\n\n**Common Mistakes:**\n- Using `&&` with `0` (falsy but renders '0'). Example: `{count && \u003Cspan>Count: {count}\u003C\u002Fspan>}` renders '0' when count is 0. Fix: `{count > 0 && \u003Cspan>Count: {count}\u003C\u002Fspan>}`.\n- Forgetting to return `null` for else case.\n- Complex nested ternaries hurting readability.\n\n**Interview Follow-ups:**\n- What is the difference between `&&` and ternary when the left side is falsy?\n- Can you use `switch` inside JSX? (No, but you can extract to a function)\n- How do you conditionally render a component without wrapping it in a div?\n\n**Best Practices:**\n- Prefer early returns for simple conditions.\n- Use ternary for simple if-else inside JSX.\n- Use `&&` only when you want to render nothing on false.\n- Extract complex condition logic into a separate function or component.\n\n**Performance Considerations:**\n- Re-rendering still evaluates conditions; no extra cost.\n- Avoid creating new components inline in conditions (causes unmount\u002Fremount).\n\n**Production Recommendations:**\n- Use `React.memo` on components that are conditionally rendered to prevent unnecessary re-renders when props don't change.\n\n**Node.js \u002F SSR Behavior:**\nConditions are evaluated during SSR, and only the true branch is rendered to HTML.\n\n**Latest React Patterns:**\n- Using fragments `\u003C>` to avoid extra divs when conditionally rendering adjacent elements.\n- React 18's Suspense for declarative loading states.\n\n**TypeScript Example:**\n```tsx\ninterface ConditionalProps {\n  status: 'loading' | 'error' | 'success';\n  data?: string;\n}\n\nconst Component: React.FC\u003CConditionalProps> = ({ status, data }) => {\n  if (status === 'loading') return \u003Cdiv>Loading...\u003C\u002Fdiv>;\n  if (status === 'error') return \u003Cdiv>Error occurred\u003C\u002Fdiv>;\n  return \u003Cdiv>{data}\u003C\u002Fdiv>;\n};\n```\n\n**Interview Tip:**\nExplain that there's no special \"if\" directive; you just use plain JavaScript. Emphasize that `0` is falsy but renders as text, so always use explicit conditions when numbers can be zero.\n\n**Common Follow-up:**\n\"How do you conditionally render a list item with a key?\" (Keep key on the element that is always present, or move condition inside the component)\n\n**Real-world Example:**\nDashboard with different widgets based on user permissions:\n```jsx\n{user.canViewAnalytics && \u003CAnalyticsWidget \u002F>}\n{user.canViewReports && \u003CReportsWidget \u002F>}\n```\n\n**Advanced Notes:**\nReact's reconciliation algorithm treats switching between component types as unmounting the old and mounting the new, losing internal state. To preserve state, keep the same component type and use props to change behavior, or use `key` to force remount.",[62,20,63],"conditional-rendering","rendering",{"id":65,"category":24,"question":66,"answer":67,"level":10,"tags":68},8,"How do you render lists in React? Explain the importance of keys and common patterns.","**Concept Explanation:**\nRendering lists in React typically uses the `map()` function to transform an array of data into an array of JSX elements. Each element in the array must have a unique `key` prop to help React identify which items have changed, been added, or removed. Keys should be stable, predictable, and unique among siblings.\n\n**Syntax Explanation:**\n```jsx\nconst items = ['Apple', 'Banana', 'Cherry'];\n\nfunction FruitList() {\n  return (\n    \u003Cul>\n      {items.map((fruit, index) => (\n        \u003Cli key={index}>{fruit}\u003C\u002Fli>\n      ))}\n    \u003C\u002Ful>\n  );\n}\n```\n\n**Code Example:**\n```jsx\nimport { useState } from 'react';\n\nfunction TodoList() {\n  const [todos, setTodos] = useState([\n    { id: 1, text: 'Learn React', completed: false },\n    { id: 2, text: 'Build a project', completed: false }\n  ]);\n\n  const addTodo = () => {\n    const newTodo = { id: Date.now(), text: 'New task', completed: false };\n    setTodos([...todos, newTodo]);\n  };\n\n  const toggleTodo = (id) => {\n    setTodos(todos.map(todo =>\n      todo.id === id ? { ...todo, completed: !todo.completed } : todo\n    ));\n  };\n\n  return (\n    \u003Cdiv>\n      \u003Cbutton onClick={addTodo}>Add Todo\u003C\u002Fbutton>\n      \u003Cul>\n        {todos.map(todo => (\n          \u003Cli key={todo.id} onClick={() => toggleTodo(todo.id)}>\n            \u003Cspan style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}>\n              {todo.text}\n            \u003C\u002Fspan>\n          \u003C\u002Fli>\n        ))}\n      \u003C\u002Ful>\n    \u003C\u002Fdiv>\n  );\n}\n```\n\n**Execution Flow:**\n1. Component renders, `map` runs, creating an array of React elements.\n2. React uses `key` to match elements in the previous and new virtual DOM trees.\n3. If key matches, React updates the existing DOM element.\n4. If key is new, React adds a new element.\n5. If key is missing, React removes the element.\n\n**Reactivity Explanation:**\nWhen the source array changes (via setState), React re-runs `map` and computes the new list. Keys allow React to reuse DOM nodes efficiently, preserving component state and minimizing DOM manipulations.\n\n**Practical Usage:**\n- Displaying API data (users, products, posts).\n- Building dynamic tables or grids.\n- Creating navigation menus from configuration.\n\n**Common Mistakes:**\n- Using array index as key when the list can change order (add\u002Fremove\u002Fsort). This can cause bugs with component state and poor performance.\n- Using random value as key (e.g., `Math.random()`) – creates new keys on every render, defeating reuse.\n- Forgetting the `key` prop – React will warn and default to index, but may cause issues.\n- Using key on a fragment (`\u003C>`) – you need `\u003CFragment key={id}>` or `\u003CReact.Fragment key={id}>`.\n\n**Interview Follow-ups:**\n- Why are keys important? What happens if you don't provide them?\n- When is it safe to use index as key?\n- How does React use keys during reconciliation?\n\n**Best Practices:**\n- Use stable, unique IDs from your data (database IDs, UUIDs).\n- Only use index as key if list is static and won't be reordered\u002Ffiltered.\n- Place `key` on the outermost element inside the map, not on fragments unless using `\u003CFragment key={...}>`.\n\n**Performance Considerations:**\n- Keys help React avoid unnecessary DOM mutations. Without proper keys, React may remount components instead of updating them.\n- For large lists, consider virtualization (react-window, react-virtualized).\n\n**Production Recommendations:**\n- When fetching data, ensure each item has a unique identifier.\n- Use `useMemo` to memoize the mapped list if the transformation is expensive.\n\n**Node.js \u002F SSR Behavior:**\nKeys are not rendered to the DOM; they are used internally by React on the server as well for reconciliation during hydration.\n\n**Latest React Patterns:**\n- React 18 automatically batches state updates, including list updates.\n- Use `react-query` for paginated or infinite list data.\n\n**TypeScript Example:**\n```tsx\ninterface Todo {\n  id: number;\n  text: string;\n  completed: boolean;\n}\n\nconst TodoList: React.FC\u003C{ todos: Todo[] }> = ({ todos }) => {\n  return (\n    \u003Cul>\n      {todos.map((todo) => (\n        \u003Cli key={todo.id}>{todo.text}\u003C\u002Fli>\n      ))}\n    \u003C\u002Ful>\n  );\n};\n```\n\n**Interview Tip:**\nEmphasize that keys help with performance and state preservation. Explain the difference between using index vs ID with a concrete example: reordering items with index keys causes checkbox state to move incorrectly.\n\n**Common Follow-up:**\n\"What is the difference between using `key` on a fragment vs a wrapper div?\"\n\n**Real-world Example:**\nChat message list: messages are sorted by timestamp, and new messages are added to the bottom. Using stable IDs (message UUID) ensures that React correctly updates only the new message instead of re-rendering the whole list.\n\n**Advanced Notes:**\nReact uses keys for diffing algorithm: when children have keys, React uses a map to match new children with old children. Without keys, it falls back to a less efficient sequential comparison. Keys must be unique only among siblings, not globally unique.",[69,70,63,71],"lists","keys","arrays",{"id":73,"category":74,"question":75,"answer":76,"level":10,"tags":77},9,"Forms","What are controlled and uncontrolled components in React forms? Provide examples and use cases.","**Concept Explanation:**\nIn React, form elements can be either controlled or uncontrolled. A **controlled component** has its value controlled by React state; the component's value is set via `value` prop and changes are handled by `onChange`. An **uncontrolled component** maintains its own internal DOM state; you access the value using a ref.\n\n**Syntax Explanation:**\n```jsx\n\u002F\u002F Controlled component\nfunction ControlledForm() {\n  const [name, setName] = useState('');\n  return \u003Cinput value={name} onChange={e => setName(e.target.value)} \u002F>;\n}\n\n\u002F\u002F Uncontrolled component\nfunction UncontrolledForm() {\n  const inputRef = useRef(null);\n  const handleSubmit = () => console.log(inputRef.current.value);\n  return \u003Cinput ref={inputRef} defaultValue=\"\" \u002F>;\n}\n```\n\n**Code Example:**\n```jsx\n\u002F\u002F Controlled – full control\nfunction SignupForm() {\n  const [formData, setFormData] = useState({ email: '', password: '' });\n  const [errors, setErrors] = useState({});\n\n  const handleChange = (e) => {\n    const { name, value } = e.target;\n    setFormData(prev => ({ ...prev, [name]: value }));\n    \u002F\u002F Real-time validation\n    if (name === 'email' && !value.includes('@')) {\n      setErrors(prev => ({ ...prev, email: 'Invalid email' }));\n    } else {\n      setErrors(prev => ({ ...prev, email: '' }));\n    }\n  };\n\n  const handleSubmit = (e) => {\n    e.preventDefault();\n    console.log(formData);\n  };\n\n  return (\n    \u003Cform onSubmit={handleSubmit}>\n      \u003Cinput name=\"email\" value={formData.email} onChange={handleChange} \u002F>\n      {errors.email && \u003Cspan>{errors.email}\u003C\u002Fspan>}\n      \u003Cinput name=\"password\" type=\"password\" value={formData.password} onChange={handleChange} \u002F>\n      \u003Cbutton type=\"submit\">Sign Up\u003C\u002Fbutton>\n    \u003C\u002Fform>\n  );\n}\n\n\u002F\u002F Uncontrolled – simpler but less control\nfunction SimpleForm() {\n  const nameRef = useRef();\n  const handleSubmit = (e) => {\n    e.preventDefault();\n    alert(nameRef.current.value);\n  };\n  return (\n    \u003Cform onSubmit={handleSubmit}>\n      \u003Cinput ref={nameRef} defaultValue=\"John\" \u002F>\n      \u003Cbutton type=\"submit\">Submit\u003C\u002Fbutton>\n    \u003C\u002Fform>\n  );\n}\n```\n\n**Execution Flow:**\n- **Controlled:** Every keystroke triggers state update → component re-renders → input gets new value from state.\n- **Uncontrolled:** DOM manages value internally. React only reads value via ref when needed (e.g., form submission).\n\n**Reactivity Explanation:**\nControlled components are reactive: state drives the UI. Uncontrolled components are not reactive; the DOM is the source of truth.\n\n**Practical Usage:**\n- **Controlled:** When you need real-time validation, dynamic form fields, or to enforce input format.\n- **Uncontrolled:** Simple forms, file inputs (which are always uncontrolled), integrating with non-React code, or when you don't need to react to every change.\n\n**Common Mistakes:**\n- Forgetting to set `value` prop on controlled input (makes it read-only).\n- Using `defaultValue` in controlled component (should use `value`).\n- Using `value` in uncontrolled component without an `onChange` (makes it read-only).\n- Not using `defaultValue` for uncontrolled initial value.\n\n**Interview Follow-ups:**\n- When would you choose uncontrolled over controlled?\n- How do you handle file inputs? (They are always uncontrolled)\n- What is the `defaultValue` prop used for?\n\n**Best Practices:**\n- Prefer controlled components for most form use cases (predictable state, easier validation).\n- Use uncontrolled for file inputs and simple forms with minimal interaction.\n- Use libraries like `react-hook-form` for complex forms (they handle both patterns).\n\n**Performance Considerations:**\n- Controlled components cause re-renders on every keystroke – fine for most cases, but for very large forms with many inputs, consider debouncing or using uncontrolled + refs.\n- Uncontrolled components do not cause re-renders on input changes, but you lose reactive UI updates.\n\n**Production Recommendations:**\n- For production forms, use `react-hook-form` – it uses uncontrolled but with validation and performance optimizations.\n- Always provide validation feedback in controlled components.\n\n**Node.js \u002F SSR Behavior:**\nControlled components can be initialized with server-provided state. Uncontrolled components will have `defaultValue` from server-rendered HTML.\n\n**Latest React Patterns:**\n- React Hook Form leverages uncontrolled components for performance.\n- Use `useId()` to generate unique IDs for accessibility.\n\n**TypeScript Example:**\n```tsx\nconst [email, setEmail] = useState\u003Cstring>('');\nconst emailRef = useRef\u003CHTMLInputElement>(null);\n\n\u002F\u002F Controlled\n\u003Cinput value={email} onChange={(e: React.ChangeEvent\u003CHTMLInputElement>) => setEmail(e.target.value)} \u002F>\n\u002F\u002F Uncontrolled\n\u003Cinput ref={emailRef} defaultValue=\"\" \u002F>\n```\n\n**Interview Tip:**\nExplain that controlled components align with React's declarative model, making the UI a function of state. Uncontrolled components are closer to traditional HTML forms and are useful for simple cases or integrating with non-React code.\n\n**Common Follow-up:**\n\"How do you handle complex forms with many fields?\" (Use `useReducer` or form libraries like Formik or react-hook-form)\n\n**Real-world Example:**\nA login form with email validation and disabled button until both fields are filled – controlled component makes this trivial.\n\n**Advanced Notes:**\nReact's `value` vs `defaultValue`: `defaultValue` sets the initial DOM value but doesn't control subsequent updates. For textareas and select elements, similar principles apply. For checkboxes and radio buttons, `checked` vs `defaultChecked`.",[78,79,80,81],"forms","controlled","uncontrolled","inputs",{"id":83,"category":84,"question":85,"answer":86,"level":10,"tags":87},10,"Hooks","What is useEffect? How does it work for side effects and lifecycle simulation?","**Concept Explanation:**\n`useEffect` is a hook that lets you perform side effects in functional components. It runs after the browser paints (by default). It can mimic `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` by controlling its dependency array and return cleanup function.\n\n**Syntax Explanation:**\n```jsx\nuseEffect(() => {\n  \u002F\u002F Effect code (runs after render)\n  return () => {\n    \u002F\u002F Cleanup (runs before next effect or unmount)\n  };\n}, [dependencies]); \u002F\u002F Re-run when dependencies change\n```\n\n**Code Example:**\n```jsx\nimport { useState, useEffect } from 'react';\n\nfunction UserProfile({ userId }) {\n  const [user, setUser] = useState(null);\n  const [loading, setLoading] = useState(true);\n\n  \u002F\u002F componentDidMount + componentDidUpdate (when userId changes)\n  useEffect(() => {\n    let isMounted = true;\n    setLoading(true);\n\n    fetch(`\u002Fapi\u002Fusers\u002F${userId}`)\n      .then(res => res.json())\n      .then(data => {\n        if (isMounted) {\n          setUser(data);\n          setLoading(false);\n        }\n      });\n\n    \u002F\u002F Cleanup: runs before next effect or unmount\n    return () => {\n      isMounted = false;\n    };\n  }, [userId]); \u002F\u002F Re-run when userId changes\n\n  \u002F\u002F componentDidMount only (empty deps)\n  useEffect(() => {\n    console.log('Component mounted');\n    return () => console.log('Component will unmount');\n  }, []);\n\n  \u002F\u002F componentDidUpdate (no deps array – runs after every render)\n  useEffect(() => {\n    console.log('Component rendered');\n  });\n\n  if (loading) return \u003Cdiv>Loading...\u003C\u002Fdiv>;\n  return \u003Cdiv>{user.name}\u003C\u002Fdiv>;\n}\n```\n\n**Execution Flow:**\n1. React renders the component (calls the function).\n2. After painting to screen, React flushes the effect queue.\n3. React runs cleanup function from previous effect (if dependencies changed).\n4. React runs current effect.\n5. For dependency array: React compares previous and current values using `Object.is`.\n\n**Reactivity Explanation:**\n`useEffect` reacts to changes in its dependency array. When state\u002Fprops change and cause a re-render, React compares dependencies; if any changed, it runs the cleanup (if exists) and then the effect again.\n\n**Practical Usage:**\n- Data fetching (API calls).\n- Subscribing to events (resize, scroll, WebSocket).\n- Manually changing the DOM.\n- Setting up timers (setInterval, setTimeout).\n- Logging.\n\n**Common Mistakes:**\n- Missing dependencies (can cause stale closures).\n- Including unnecessary dependencies (causes over-firing).\n- Not cleaning up subscriptions (memory leaks).\n- Using async function directly as effect callback (must be wrapped).\n- Infinite loops when setting state without proper dependencies.\n\n**Interview Follow-ups:**\n- What is the difference between `useEffect` and `useLayoutEffect`?\n- How do you fetch data with `useEffect`?\n- What is the purpose of the cleanup function?\n\n**Best Practices:**\n- Always specify explicit dependencies (use `eslint-plugin-react-hooks`).\n- Extract complex logic into custom hooks.\n- Use abort controllers to cancel fetch requests in cleanup.\n- Keep effects focused on a single responsibility.\n\n**Performance Considerations:**\n- Effects run after paint, so they don't block the UI.\n- Use `useCallback` and `useMemo` to stabilize dependencies.\n- For animations, use `useLayoutEffect` for synchronous updates before paint.\n\n**Production Recommendations:**\n- Use `react-query` or `swr` for data fetching instead of raw `useEffect`.\n- Use `useEffect` with cleanup for event listeners to avoid duplicates.\n\n**Node.js \u002F SSR Behavior:**\n`useEffect` does not run during server-side rendering; only on the client after hydration.\n\n**Latest React Patterns:**\n- React 18's automatic batching can affect effect timing.\n- Use `useInsertionEffect` for CSS-in-JS libraries.\n\n**TypeScript Example:**\n```tsx\nuseEffect(() => {\n  const timer = setTimeout(() => {\n    console.log('Delayed');\n  }, 1000);\n  return () => clearTimeout(timer);\n}, []);\n```\n\n**Interview Tip:**\nExplain that the dependency array tells React when to re-run the effect. Empty array = run once after mount. No array = run after every render. Array with values = run when those values change.\n\n**Common Follow-up:**\n\"How do you handle async\u002Fawait in useEffect?\" (Define async function inside effect, then call it)\n\n**Real-world Example:**\nChat app: `useEffect` to connect to WebSocket when component mounts, return cleanup to disconnect.\n\n**Advanced Notes:**\nReact uses a commit phase (DOM updates) and then a passive effect phase (useEffect). Effects are always executed after layout and paint, making them non-blocking. Multiple effects run in order of declaration.",[88,89,90,47],"useEffect","side-effects","lifecycle",{"id":92,"category":84,"question":93,"answer":94,"level":10,"tags":95},11,"What is the useState hook? Provide multiple examples and explain batch updates.","**Concept Explanation:**\n`useState` is a React hook that adds local state to functional components. It returns an array with the current state value and a setter function. When the setter is called, React schedules a re-render of the component with the new state value. React batches multiple state updates in event handlers for performance.\n\n**Syntax Explanation:**\n```jsx\nimport { useState } from 'react';\n\nconst [state, setState] = useState(initialValue);\nconst [state, setState] = useState(() => expensiveInitialValue()); \u002F\u002F lazy initialization\n```\n\n**Code Example:**\n```jsx\nfunction Counter() {\n  const [count, setCount] = useState(0);\n  const [step, setStep] = useState(1);\n\n  \u002F\u002F Simple update\n  const increment = () => setCount(count + step);\n\n  \u002F\u002F Functional update (safe for async or multiple updates)\n  const incrementTwice = () => {\n    setCount(prev => prev + step);\n    setCount(prev => prev + step); \u002F\u002F correctly adds step twice\n  };\n\n  \u002F\u002F Object state\n  const [user, setUser] = useState({ name: '', age: 0 });\n  const updateName = (name) => {\n    setUser(prev => ({ ...prev, name })); \u002F\u002F spread previous state\n  };\n\n  return (\n    \u003Cdiv>\n      \u003Cp>Count: {count}\u003C\u002Fp>\n      \u003Cbutton onClick={increment}>Increment\u003C\u002Fbutton>\n      \u003Cbutton onClick={incrementTwice}>+{step} twice\u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  );\n}\n\n\u002F\u002F Batching example\nfunction BatchedUpdates() {\n  const [a, setA] = useState(0);\n  const [b, setB] = useState(0);\n\n  const handleClick = () => {\n    \u002F\u002F React batches these updates – only one re-render\n    setA(1);\n    setB(2);\n  };\n\n  \u002F\u002F In async callbacks, React \u003C18 does not batch, React 18+ does\n  const handleAsyncClick = async () => {\n    await fetchSomething();\n    setA(1);\n    setB(2); \u002F\u002F React 18+ batches, earlier versions cause two re-renders\n  };\n\n  return \u003Cbutton onClick={handleClick}>Update both\u003C\u002Fbutton>;\n}\n```\n\n**Execution Flow:**\n1. Component renders, `useState` initializes state (once).\n2. User calls setter with new value.\n3. React queues an update and marks component as dirty.\n4. If inside event handler, React batches multiple setter calls.\n5. React re-renders component with updated state.\n6. `useState` returns the new state value.\n\n**Reactivity Explanation:**\nState updates are asynchronous for performance. Between the setter call and the re-render, the state variable still holds the old value. Functional updates give you access to the pending previous state, ensuring correctness when multiple updates are queued.\n\n**Practical Usage:**\n- Tracking form input values.\n- Toggle UI elements (modal open\u002Fclose).\n- Managing simple component-specific data.\n\n**Common Mistakes:**\n- Mutating state directly: `state.value = newValue` instead of `setState(...)`.\n- Assuming state updates are synchronous.\n- Not using functional updates when next state depends on previous state in async callbacks.\n- Forgetting to spread previous state when updating object\u002Farray.\n\n**Interview Follow-ups:**\n- How does React know which `useState` call corresponds to which state?\n- What is the difference between `setState(prev => prev + 1)` and `setState(state + 1)`?\n- What is React's automatic batching and how does it work?\n\n**Best Practices:**\n- Use multiple `useState` calls for unrelated state variables.\n- Use functional updates when new state depends on previous state.\n- Use `useReducer` for complex state logic.\n- For objects\u002Farrays, always create new copies (immutability).\n\n**Performance Considerations:**\n- Batching reduces unnecessary re-renders.\n- Lazy initialization (`useState(() => compute())`) avoids recomputing initial value on every render.\n\n**Production Recommendations:**\n- Use `useState` for component-local UI state.\n- For global or complex state, consider Zustand, Redux, or Context API.\n\n**Node.js \u002F SSR Behavior:**\n`useState` initial state is evaluated during SSR but no updates occur.\n\n**Latest React Patterns:**\n- React 18 automatically batches updates even in promises, timeouts, and event handlers.\n- `flushSync` can force synchronous updates if needed.\n\n**TypeScript Example:**\n```tsx\nconst [count, setCount] = useState\u003Cnumber>(0);\nconst [user, setUser] = useState\u003C{ name: string } | null>(null);\nconst [items, setItems] = useState\u003Cstring[]>([]);\n```\n\n**Interview Tip:**\nExplain that React uses a persistent reference to state based on the order of hooks. Emphasize immutability: always replace state rather than mutate.\n\n**Common Follow-up:**\n\"Why does React re-render when state changes?\" (To reflect new state in UI)\n\n**Real-world Example:**\nShopping cart item quantity: `setQuantity(prev => prev + 1)` inside an async event handler ensures you increment correctly even if multiple updates are batched.\n\n**Advanced Notes:**\nReact's `setState` (in classes) merges objects, but `useState` setter replaces the state. For objects, you must manually spread previous state. The setter function identity is stable (won't change between renders), so it can be omitted from `useEffect` dependencies.",[46,45,96,47],"batching",{"id":98,"category":99,"question":100,"answer":101,"level":10,"tags":102},12,"Routing","How does React Router work? Explain basic routing, navigation, and route parameters.","**Concept Explanation:**\nReact Router is a standard library for routing in React applications. It enables navigation between different components, changing the URL, and maintaining UI state. It uses a declarative approach with components like `BrowserRouter`, `Routes`, `Route`, `Link`, and hooks like `useNavigate`, `useParams`, `useLocation`.\n\n**Syntax Explanation:**\n```jsx\nimport { BrowserRouter, Routes, Route, Link, useNavigate } from 'react-router-dom';\n\nfunction App() {\n  return (\n    \u003CBrowserRouter>\n      \u003Cnav>\n        \u003CLink to=\"\u002F\">Home\u003C\u002FLink>\n        \u003CLink to=\"\u002Fabout\">About\u003C\u002FLink>\n      \u003C\u002Fnav>\n      \u003CRoutes>\n        \u003CRoute path=\"\u002F\" element={\u003CHome \u002F>} \u002F>\n        \u003CRoute path=\"\u002Fabout\" element={\u003CAbout \u002F>} \u002F>\n        \u003CRoute path=\"\u002Fuser\u002F:id\" element={\u003CUserProfile \u002F>} \u002F>\n      \u003C\u002FRoutes>\n    \u003C\u002FBrowserRouter>\n  );\n}\n\nfunction UserProfile() {\n  const { id } = useParams(); \u002F\u002F Get route parameter\n  const navigate = useNavigate();\n  return (\n    \u003Cdiv>\n      \u003Ch1>User {id}\u003C\u002Fh1>\n      \u003Cbutton onClick={() => navigate('\u002F')}>Go Home\u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  );\n}\n```\n\n**Code Example:**\n```jsx\nimport { BrowserRouter, Routes, Route, Link, NavLink, useNavigate, useLocation, Outlet } from 'react-router-dom';\n\n\u002F\u002F Layout with nested routes\nfunction Layout() {\n  return (\n    \u003Cdiv>\n      \u003Cheader>\n        \u003CNavLink to=\"\u002F\" className={({ isActive }) => isActive ? 'active' : ''}>Home\u003C\u002FNavLink>\n        \u003CNavLink to=\"\u002Fproducts\">Products\u003C\u002FNavLink>\n      \u003C\u002Fheader>\n      \u003COutlet \u002F> {\u002F* Child routes render here *\u002F}\n    \u003C\u002Fdiv>\n  );\n}\n\nfunction Products() {\n  const products = [{ id: 1, name: 'Laptop' }, { id: 2, name: 'Phone' }];\n  return (\n    \u003Cdiv>\n      {products.map(p => \u003CLink key={p.id} to={`\u002Fproducts\u002F${p.id}`}>{p.name}\u003C\u002FLink>)}\n    \u003C\u002Fdiv>\n  );\n}\n\nfunction ProductDetail() {\n  const { id } = useParams();\n  const navigate = useNavigate();\n  const location = useLocation();\n\n  useEffect(() => {\n    console.log('Current location:', location.pathname);\n  }, [location]);\n\n  return (\n    \u003Cdiv>\n      \u003Ch2>Product {id}\u003C\u002Fh2>\n      \u003Cbutton onClick={() => navigate(-1)}>Go Back\u003C\u002Fbutton>\n      \u003Cbutton onClick={() => navigate('\u002F')}>Home\u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  );\n}\n\n\u002F\u002F Main App with nested routes\nfunction App() {\n  return (\n    \u003CBrowserRouter>\n      \u003CRoutes>\n        \u003CRoute path=\"\u002F\" element={\u003CLayout \u002F>}>\n          \u003CRoute index element={\u003CHome \u002F>} \u002F>\n          \u003CRoute path=\"products\" element={\u003CProducts \u002F>} \u002F>\n          \u003CRoute path=\"products\u002F:id\" element={\u003CProductDetail \u002F>} \u002F>\n        \u003C\u002FRoute>\n        \u003CRoute path=\"*\" element={\u003CNotFound \u002F>} \u002F>\n      \u003C\u002FRoutes>\n    \u003C\u002FBrowserRouter>\n  );\n}\n```\n\n**Execution Flow:**\n1. `BrowserRouter` listens to URL changes using the History API.\n2. When URL changes, React Router matches the current path against defined `Route` paths.\n3. The matching `Route` renders its `element` prop.\n4. `Link` components prevent default navigation and use `navigate` instead.\n\n**Reactivity Explanation:**\nWhen the URL changes, React Router updates its context, causing matching components to re-render. `useParams`, `useLocation`, `useNavigate` hooks react to these changes.\n\n**Practical Usage:**\n- Multi-page single-page applications.\n- Deep linking and shareable URLs.\n- Protected routes (authentication).\n\n**Common Mistakes:**\n- Forgetting to wrap routes with `BrowserRouter`.\n- Using `\u003Ca href>` instead of `\u003CLink>` causing full page reload.\n- Not handling trailing slashes correctly.\n- Missing catch-all route (`path=\"*\"`).\n\n**Interview Follow-ups:**\n- What is the difference between `BrowserRouter` and `HashRouter`?\n- How do you implement protected routes?\n- What is code splitting with React Router?\n\n**Best Practices:**\n- Use `NavLink` for navigation menus to get active styling.\n- Use nested routes with `Outlet` for layouts.\n- Use `useNavigate` for programmatic navigation.\n- Use `useLocation` to read query parameters.\n\n**Performance Considerations:**\n- Code-split route components with `React.lazy` and Suspense.\n- Use `Route` `element` prop with inline components carefully (creates new component on render).\n\n**Production Recommendations:**\n- Use React Router v6 (latest).\n- Configure server to handle client-side routing (fallback to index.html).\n- Use `createBrowserRouter` with data loading features.\n\n**Node.js \u002F SSR Behavior:**\nReact Router supports static routing on server. Use `StaticRouter` for SSR with Node.js.\n\n**Latest React Patterns:**\n- React Router v6 introduced `createBrowserRouter` and `RouterProvider` for data loading.\n- `useLoaderData`, `useActionData` for data fetching in routes.\n\n**TypeScript Example:**\n```tsx\nimport { useParams } from 'react-router-dom';\n\ninterface Params {\n  id: string;\n}\n\nfunction ProductDetail() {\n  const { id } = useParams\u003CParams>();\n  \u002F\u002F id is string | undefined\n}\n```\n\n**Interview Tip:**\nExplain that React Router enables client-side routing without server round trips. Contrast with traditional multi-page apps.\n\n**Common Follow-up:**\n\"How do you pass state between routes without URL parameters?\" (Use `navigate('\u002Fprofile', { state: { userId: 123 } })`)\n\n**Real-world Example:**\nE-commerce site: product list page routes to product detail with `:id` param. Cart uses navigate with state to preserve items.\n\n**Advanced Notes:**\nReact Router v6 introduced relative routes and automatic ranking of routes. The `element` prop uses React.createElement, not a function call, to avoid re-creation on every render.",[103,104,105,106],"routing","react-router","navigation","spa",{"id":108,"category":109,"question":110,"answer":111,"level":10,"tags":112},13,"API Integration","How do you fetch data in React? Compare fetch API with libraries like React Query.","**Concept Explanation:**\nData fetching in React can be done using the native `fetch` API inside `useEffect`, or using specialized libraries like React Query (TanStack Query), SWR, or Apollo Client. The native approach requires manual state management (loading, error, data) and cache handling, while libraries provide built-in caching, retries, and background refetching.\n\n**Syntax Explanation:**\n```jsx\n\u002F\u002F Native fetch with useEffect\nfunction UserProfile({ userId }) {\n  const [user, setUser] = useState(null);\n  const [loading, setLoading] = useState(true);\n  const [error, setError] = useState(null);\n\n  useEffect(() => {\n    let isMounted = true;\n    setLoading(true);\n    fetch(`\u002Fapi\u002Fusers\u002F${userId}`)\n      .then(res => res.json())\n      .then(data => {\n        if (isMounted) {\n          setUser(data);\n          setLoading(false);\n        }\n      })\n      .catch(err => {\n        if (isMounted) setError(err);\n      });\n    return () => { isMounted = false; };\n  }, [userId]);\n\n  if (loading) return \u003Cdiv>Loading...\u003C\u002Fdiv>;\n  if (error) return \u003Cdiv>Error: {error.message}\u003C\u002Fdiv>;\n  return \u003Cdiv>{user.name}\u003C\u002Fdiv>;\n}\n```\n\n**Code Example with React Query:**\n```jsx\nimport { useQuery } from '@tanstack\u002Freact-query';\n\nfunction fetchUser(userId) {\n  return fetch(`\u002Fapi\u002Fusers\u002F${userId}`).then(res => res.json());\n}\n\nfunction UserProfile({ userId }) {\n  const { data, isLoading, error, refetch } = useQuery({\n    queryKey: ['user', userId],\n    queryFn: () => fetchUser(userId),\n    staleTime: 5 * 60 * 1000, \u002F\u002F 5 minutes\n    retry: 3,\n  });\n\n  if (isLoading) return \u003Cdiv>Loading...\u003C\u002Fdiv>;\n  if (error) return \u003Cdiv>Error: {error.message}\u003C\u002Fdiv>;\n  return (\n    \u003Cdiv>\n      \u003Cp>{data.name}\u003C\u002Fp>\n      \u003Cbutton onClick={() => refetch()}>Refresh\u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  );\n}\n\n\u002F\u002F Mutations (POST, PUT, DELETE)\nimport { useMutation, useQueryClient } from '@tanstack\u002Freact-query';\n\nfunction AddUser() {\n  const queryClient = useQueryClient();\n  const mutation = useMutation({\n    mutationFn: (newUser) => fetch('\u002Fapi\u002Fusers', { method: 'POST', body: JSON.stringify(newUser) }),\n    onSuccess: () => {\n      queryClient.invalidateQueries({ queryKey: ['users'] });\n    },\n  });\n\n  return \u003Cbutton onClick={() => mutation.mutate({ name: 'Alice' })}>Add User\u003C\u002Fbutton>;\n}\n```\n\n**Execution Flow (React Query):**\n1. Component mounts, `useQuery` triggers fetch.\n2. Returns `isLoading: true` initially.\n3. Fetch completes, caches result under `['user', userId]`.\n4. Component re-renders with data.\n5. On refetch or window focus, background refetch occurs.\n\n**Reactivity Explanation:**\nReact Query tracks query keys. When the key changes (e.g., userId changes), it automatically refetches. It also deduplicates concurrent requests for the same key.\n\n**Practical Usage:**\n- Native fetch: simple apps, learning purposes, when you need minimal dependencies.\n- React Query: production apps with complex data synchronization needs.\n\n**Common Mistakes:**\n- Forgetting cleanup for fetch to prevent state updates on unmounted components.\n- Not handling loading\u002Ferror states.\n- Fetching the same data in multiple components (causing duplicate requests).\n\n**Interview Follow-ups:**\n- How do you prevent race conditions in fetch with `useEffect`? (Using abort controller or cleanup flag)\n- What are the benefits of React Query over manual fetch?\n- How do you cache API responses in React?\n\n**Best Practices:**\n- Use AbortController to cancel in-flight fetch on unmount or dependency change.\n- Extract fetch logic into custom hooks.\n- Use React Query for automatic caching, background refetching, and optimistic updates.\n\n**Performance Considerations:**\n- React Query caches data, reducing network requests.\n- Use `staleTime` to control when to refetch.\n- `useQuery` also deduplicates requests within a short window.\n\n**Production Recommendations:**\n- Use React Query (or SWR) for data fetching in production.\n- Set up global error handling and retry policies.\n- Use `ReactQueryDevtools` for debugging.\n\n**Node.js \u002F SSR Behavior:**\nReact Query supports SSR via `initialData` or `dehydrate`\u002F`hydrate`. Native fetch in `useEffect` does not run on server.\n\n**Latest React Patterns:**\n- React Server Components allow fetching data directly in async components.\n- Suspense with data fetching (React Query supports Suspense mode).\n\n**TypeScript Example:**\n```tsx\ninterface User {\n  id: number;\n  name: string;\n}\n\nconst { data } = useQuery\u003CUser>({\n  queryKey: ['user', userId],\n  queryFn: () => fetchUser(userId),\n});\n```\n\n**Interview Tip:**\nHighlight that React Query abstracts away loading, error, caching, and retries, making code much cleaner and production-ready.\n\n**Common Follow-up:**\n\"How do you handle mutations and optimistic updates?\" (useMutation with onMutate rollback)\n\n**Real-world Example:**\nA dashboard that displays real-time stock prices – React Query can automatically refetch on window focus and set polling intervals.\n\n**Advanced Notes:**\nReact Query also supports pagination, infinite queries, and dependent queries. It integrates with WebSocket and other data sources.",[113,114,115,88],"data-fetching","api","react-query",{"id":117,"category":24,"question":118,"answer":119,"level":10,"tags":120},14,"What is the difference between props and state in React?","**Concept Explanation:**\nProps (short for properties) are read-only data passed from parent to child component. State is data that is managed within a component and can be changed by that component. Props are immutable from the child's perspective; state is mutable using setter functions.\n\n**Syntax Explanation:**\n```jsx\n\u002F\u002F Parent passes props\nfunction Parent() {\n  const [count, setCount] = useState(0); \u002F\u002F state\n  return \u003CChild count={count} \u002F>; \u002F\u002F props\n}\n\n\u002F\u002F Child receives props\nfunction Child({ count }) { \u002F\u002F props as parameter\n  \u002F\u002F Cannot modify count here\n  return \u003Cdiv>{count}\u003C\u002Fdiv>;\n}\n```\n\n**Code Example:**\n```jsx\nfunction UserCard({ user, onUpdate }) { \u002F\u002F props\n  const [isEditing, setIsEditing] = useState(false); \u002F\u002F state\n\n  return (\n    \u003Cdiv>\n      {isEditing ? (\n        \u003Cinput\n          defaultValue={user.name}\n          onBlur={(e) => {\n            onUpdate(e.target.value);\n            setIsEditing(false);\n          }}\n        \u002F>\n      ) : (\n        \u003Cspan onClick={() => setIsEditing(true)}>{user.name}\u003C\u002Fspan>\n      )}\n    \u003C\u002Fdiv>\n  );\n}\n\nfunction App() {\n  const [user, setUser] = useState({ name: 'Alice' }); \u002F\u002F state\n\n  return (\n    \u003CUserCard\n      user={user} \u002F\u002F prop\n      onUpdate={(newName) => setUser({ name: newName })} \u002F\u002F prop callback\n    \u002F>\n  );\n}\n```\n\n**Execution Flow:**\n- **State:** Initialized once; setter triggers re-render.\n- **Props:** Received on each render; changes from parent trigger child re-render.\n\n**Reactivity Explanation:**\nBoth props and state changes cause re-renders. State changes are internal; prop changes are external (parent-driven).\n\n**Practical Usage:**\n- **Props:** Configuration, data from parent, callback functions.\n- **State:** UI state (modal open, form input values), data that changes over time.\n\n**Common Mistakes:**\n- Trying to assign to props (they are read-only).\n- Storing props in state unnecessarily (creates two sources of truth).\n- Mutating state directly.\n\n**Interview Follow-ups:**\n- When would you use state vs props?\n- How do you derive state from props? (Use during render, not store in state)\n- What is lifting state up?\n\n**Best Practices:**\n- Keep state minimal – only store what changes.\n- Derive computed values during render.\n- Pass callbacks as props to allow child-to-parent communication.\n\n**Performance Considerations:**\n- Changing props of child component triggers child re-render (unless memoized).\n- Changing state within component triggers re-render of that component and its children.\n\n**Production Recommendations:**\n- Use TypeScript to define prop types.\n- Use React.memo to prevent unnecessary re-renders when props haven't changed.\n\n**Node.js \u002F SSR Behavior:**\nBoth props and state are initialized during SSR. State updates don't occur on server.\n\n**Latest React Patterns:**\n- Context API can be seen as \"global props\" for deep trees.\n- State management libraries (Zustand, Redux) externalize state.\n\n**TypeScript Example:**\n```tsx\ninterface ChildProps {\n  name: string;\n  onUpdate: (newName: string) => void;\n}\n\nconst Child: React.FC\u003CChildProps> = ({ name, onUpdate }) => {\n  const [localName, setLocalName] = useState(name); \u002F\u002F state\n};\n```\n\n**Interview Tip:**\nUse an analogy: props are function arguments (passed in, read-only), state is local variables (can change within function).\n\n**Common Follow-up:**\n\"How do you decide what should be props and what should be state?\" (If data is needed by parent or siblings, lift up; if only for internal UI, keep as state)\n\n**Real-world Example:**\nA form input uses state for its current value (internal), but receives an initial `defaultValue` as a prop. The final submitted value is passed back via a callback prop.\n\n**Advanced Notes:**\nReact's unidirectional data flow (props down, events up) keeps components predictable. Storing props into state can be useful for optimization but should be done carefully (using `useEffect` or lazy initialization).",[36,45,37],{"id":122,"category":123,"question":124,"answer":125,"level":10,"tags":126},15,"Styling","What are different ways to style React components? Compare CSS modules, Styled Components, and Tailwind CSS.","**Concept Explanation:**\nReact components can be styled using traditional CSS (global), CSS Modules (scoped locally), CSS-in-JS libraries (Styled Components, Emotion), utility-first frameworks (Tailwind CSS), or inline styles. Each approach has trade-offs in scoping, dynamic styling, and bundle size.\n\n**Syntax Explanation:**\n```jsx\n\u002F\u002F 1. Global CSS (import '.\u002FButton.css')\n\u003Cbutton className=\"btn-primary\">Click\u003C\u002Fbutton>\n\n\u002F\u002F 2. CSS Modules\nimport styles from '.\u002FButton.module.css';\n\u003Cbutton className={styles.primary}>Click\u003C\u002Fbutton>\n\n\u002F\u002F 3. Styled Components\nimport styled from 'styled-components';\nconst Button = styled.button`\n  background: blue;\n  color: white;\n`;\n\u003CButton>Click\u003C\u002FButton>\n\n\u002F\u002F 4. Tailwind CSS\n\u003Cbutton className=\"bg-blue-500 text-white px-4 py-2 rounded\">Click\u003C\u002Fbutton>\n\n\u002F\u002F 5. Inline styles\n\u003Cbutton style={{ backgroundColor: 'blue', color: 'white' }}>Click\u003C\u002Fbutton>\n```\n\n**Code Example:**\n```jsx\n\u002F\u002F CSS Modules (Button.module.css)\n.button { background: blue; }\n.primary { background: darkblue; }\n\n\u002F\u002F Component\nimport styles from '.\u002FButton.module.css';\nfunction Button({ variant, children }) {\n  return \u003Cbutton className={`${styles.button} ${styles[variant]}`}>{children}\u003C\u002Fbutton>;\n}\n\n\u002F\u002F Styled Components with props\nimport styled from 'styled-components';\nconst StyledButton = styled.button`\n  background: ${props => props.primary ? 'blue' : 'gray'};\n  padding: 8px 16px;\n  border-radius: 4px;\n  &:hover { opacity: 0.8; }\n`;\nfunction Button({ primary, children }) {\n  return \u003CStyledButton primary={primary}>{children}\u003C\u002FStyledButton>;\n}\n\n\u002F\u002F Tailwind CSS with conditional classes\nfunction Button({ primary, children }) {\n  return (\n    \u003Cbutton className={`px-4 py-2 rounded ${primary ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-800'}`}>\n      {children}\n    \u003C\u002Fbutton>\n  );\n}\n```\n\n**Execution Flow:**\n- **CSS Modules:** Class names are hashed at build time (e.g., `Button_button__3x7k9`).\n- **Styled Components:** Generates unique class names and injects CSS into `\u003Chead>` at runtime.\n- **Tailwind:** Utility classes are generated at build time based on used classes.\n\n**Reactivity Explanation:**\nStyled Components support dynamic styles based on props; they re-render and update CSS when props change.\n\n**Practical Usage:**\n- **CSS Modules:** Medium to large apps needing scoped CSS.\n- **Styled Components:** Component libraries, theming, dynamic styling.\n- **Tailwind:** Rapid development, consistent design system.\n\n**Common Mistakes:**\n- Using inline styles for pseudo-classes or media queries (not supported).\n- CSS Modules – forgetting to use `camelCase` for hyphenated class names when importing.\n- Styled Components – re-creating styled components inside render causing performance issues.\n\n**Interview Follow-ups:**\n- What are the advantages of CSS-in-JS?\n- How does Tailwind compare to traditional CSS?\n- What is CSS Modules scoping mechanism?\n\n**Best Practices:**\n- For libraries: Styled Components (customizable).\n- For large apps with design system: Tailwind CSS.\n- For scoped CSS without extra deps: CSS Modules.\n\n**Performance Considerations:**\n- Tailwind: small CSS bundle if using purge (removes unused classes).\n- Styled Components: runtime cost to generate and inject CSS.\n- CSS Modules: zero runtime overhead.\n\n**Production Recommendations:**\n- Use Tailwind with PurgeCSS for minimal CSS.\n- Use Styled Components with `babel-plugin-styled-components` for better debugging and smaller bundles.\n- Use CSS Modules with CSS-in-JS alternatives like Linaria (zero runtime).\n\n**Node.js \u002F SSR Behavior:**\n- CSS Modules: works fine.\n- Styled Components: supports SSR with `ServerStyleSheet` to collect CSS.\n- Tailwind: CSS is generated at build time, no SSR issues.\n\n**Latest React Patterns:**\n- React 18 with Streaming SSR – Styled Components need async sheet extraction.\n- CSS Modules are built into Next.js and Create React App.\n\n**TypeScript Example (Styled Components):**\n```tsx\ninterface ButtonProps {\n  primary?: boolean;\n}\n\nconst Button = styled.button\u003CButtonProps>`\n  background: ${props => props.primary ? 'blue' : 'gray'};\n`;\n```\n\n**Interview Tip:**\nExplain that the best choice depends on team preference, project size, and performance requirements. Mention that inline styles are rarely used for anything beyond dynamic values.\n\n**Common Follow-up:**\n\"How do you handle theming with Styled Components?\" (Use ThemeProvider)\n\n**Real-world Example:**\nA design system component library uses Styled Components for theming and dynamic props. An e-commerce frontend uses Tailwind for fast iteration.\n\n**Advanced Notes:**\nCSS Modules can be combined with PostCSS for advanced features. Styled Components supports `attrs` and `as` prop. Tailwind v4 will use CSS-first configuration.",[127,128,129,130],"styling","css-modules","styled-components","tailwind",{"id":132,"category":7,"question":133,"answer":134,"level":10,"tags":135},16,"What is the virtual DOM? How does it work and why is it important in React?","**Concept Explanation:**\nThe virtual DOM (VDOM) is a lightweight JavaScript representation of the real DOM. React uses it to improve performance by minimizing expensive direct DOM manipulations. When state changes, React creates a new virtual DOM tree, diffs it with the previous tree, computes the minimal set of changes, and applies only those changes to the real DOM.\n\n**Syntax Explanation:**\n```jsx\n\u002F\u002F React creates virtual DOM objects instead of real DOM\nconst element = \u003Ch1 className=\"title\">Hello\u003C\u002Fh1>;\n\u002F\u002F Virtual DOM representation:\n\u002F\u002F { type: 'h1', props: { className: 'title', children: 'Hello' } }\n```\n\n**Code Example (Simplified diff process):**\n```javascript\n\u002F\u002F Pseudo-code for virtual DOM diff\nfunction diff(prevVDOM, nextVDOM) {\n  if (prevVDOM.type !== nextVDOM.type) {\n    \u002F\u002F Different component type – replace node\n    return { operation: 'REPLACE', newNode: nextVDOM };\n  }\n  if (prevVDOM.props !== nextVDOM.props) {\n    \u002F\u002F Same type, different props – update props\n    return { operation: 'UPDATE_PROPS', props: nextVDOM.props };\n  }\n  \u002F\u002F Recursively diff children\n  return { operation: 'UPDATE_CHILDREN', changes: ... };\n}\n```\n\n**Execution Flow:**\n1. State or props change.\n2. React creates a new virtual DOM tree by calling component render functions.\n3. React diffs the new tree against the previous snapshot (reconciliation).\n4. React identifies which nodes changed (insert, update, delete, move).\n5. React batches these changes and updates the real DOM in a single commit phase.\n6. Browser repaints only the updated parts.\n\n**Reactivity Explanation:**\nThe virtual DOM is the mechanism that enables React's declarative programming model. You describe what the UI should look like for a given state, and React uses the virtual DOM to figure out how to update the real DOM efficiently.\n\n**Practical Usage:**\n- Avoids direct DOM manipulation, reducing bugs.\n- Enables cross-platform rendering (React Native uses same VDOM).\n- Simplifies component model.\n\n**Common Mistakes:**\n- Thinking virtual DOM is always faster than manual DOM updates (it's not, but it's more predictable).\n- Directly accessing DOM for updates when React could handle it.\n\n**Interview Follow-ups:**\n- Does React always use the virtual DOM? (Yes, for web ReactDOM)\n- How does the virtual DOM compare to real DOM manipulation?\n- What is the reconciliation algorithm?\n\n**Best Practices:**\n- Let React handle DOM updates through state\u002Fprops.\n- Use `key` props to help reconciliation.\n- Avoid manual DOM manipulation unless absolutely necessary (refs).\n\n**Performance Considerations:**\n- Virtual DOM diffing is O(n) due to heuristics.\n- Large lists need keys for efficient diffing.\n- Unnecessary re-renders can be prevented with `React.memo`.\n\n**Production Recommendations:**\n- Use React DevTools Profiler to identify inefficient re-renders.\n- Ensure stable keys in lists.\n\n**Node.js \u002F SSR Behavior:**\nVirtual DOM can be serialized to HTML on the server using `renderToString`.\n\n**Latest React Patterns:**\n- React Fiber (reconciliation rewrite) enabled incremental rendering and concurrent features.\n- React 18 introduces automatic batching and transitions.\n\n**TypeScript Example:**\n(Not applicable – virtual DOM is internal)\n\n**Interview Tip:**\nExplain that the virtual DOM is a programming concept, not a performance silver bullet. It provides a declarative API at a reasonable performance cost.\n\n**Common Follow-up:**\n\"What is the difference between React's virtual DOM and Shadow DOM?\" (Completely different concepts – Shadow DOM is a browser API for DOM encapsulation)\n\n**Real-world Example:**\nA list of 1000 items: without virtual DOM, manually updating one item would require re-rendering the entire list or complex logic. React's diffing finds the changed item and updates only that node.\n\n**Advanced Notes:**\nReact Fiber reimplemented the reconciliation algorithm with linked lists, allowing work to be interrupted, prioritized, and reused. The virtual DOM is not an actual DOM tree; it's a tree of React elements (Fiber nodes).",[13,136,63,137],"reconciliation","internals",{"id":139,"category":84,"question":140,"answer":141,"level":10,"tags":142},17,"What are React Hooks? Explain the basic hooks and their rules.","**Concept Explanation:**\nHooks are functions that let you use React features (state, lifecycle, context) in functional components without writing classes. They were introduced in React 16.8. Basic hooks include `useState` (state), `useEffect` (side effects), `useContext` (context), `useRef` (mutable references), and `useCallback`\u002F`useMemo` (optimization).\n\n**Syntax Explanation:**\n```jsx\nimport { useState, useEffect, useContext, useRef, useCallback, useMemo } from 'react';\n\nfunction Example() {\n  const [count, setCount] = useState(0);\n  const inputRef = useRef(null);\n\n  useEffect(() => {\n    document.title = `Clicked ${count} times`;\n  }, [count]);\n\n  const memoizedValue = useMemo(() => computeExpensiveValue(count), [count]);\n  const handleClick = useCallback(() => setCount(c => c + 1), []);\n\n  return \u003Cbutton onClick={handleClick}>{count}\u003C\u002Fbutton>;\n}\n```\n\n**Code Example:**\n```jsx\n\u002F\u002F Rules of hooks demonstration\nfunction MyComponent() {\n  \u002F\u002F ✅ Top-level call\n  const [name, setName] = useState('');\n  \n  \u002F\u002F ❌ Cannot call conditionally\n  \u002F\u002F if (condition) { const [x, setX] = useState(0); }\n  \n  \u002F\u002F ✅ Custom hook (calls other hooks)\n  const { data, loading } = useCustomFetch('\u002Fapi');\n  \n  useEffect(() => {\n    \u002F\u002F Effect logic\n  }, [name]);\n  \n  return \u003Cdiv>{name}\u003C\u002Fdiv>;\n}\n\n\u002F\u002F Custom hook example\nfunction useCustomFetch(url) {\n  const [data, setData] = useState(null);\n  const [loading, setLoading] = useState(true);\n  \n  useEffect(() => {\n    fetch(url).then(res => res.json()).then(setData).finally(() => setLoading(false));\n  }, [url]);\n  \n  return { data, loading };\n}\n```\n\n**Execution Flow:**\nReact maintains a linked list of hooks for each component instance. On first render, hooks are initialized. On subsequent renders, React reads the stored state from the same order. This is why hooks must be called unconditionally and in the same order every render.\n\n**Reactivity Explanation:**\nHooks allow functional components to be reactive: `useState` provides reactive state, `useEffect` reacts to state changes, `useContext` reacts to context updates.\n\n**Practical Usage:**\n- Managing component state.\n- Performing side effects (data fetching, subscriptions).\n- Accessing React context.\n- Optimizing performance.\n\n**Common Mistakes:**\n- Calling hooks after conditional returns.\n- Calling hooks in loops or nested functions.\n- Missing dependencies in `useEffect` causing stale closures.\n- Overusing `useMemo`\u002F`useCallback` prematurely.\n\n**Interview Follow-ups:**\n- Why were hooks introduced? (Better code reuse, simpler components, easier to reason)\n- How does React associate hooks with a specific component?\n- What are the rules of hooks?\n\n**Best Practices:**\n- Use ESLint plugin `eslint-plugin-react-hooks`.\n- Keep hooks at the top level of your component.\n- Name custom hooks with `use` prefix.\n\n**Performance Considerations:**\n- `useCallback` and `useMemo` can reduce child re-renders but add memory overhead.\n- Only use them when needed (when passing callbacks to memoized children).\n\n**Production Recommendations:**\n- Use `useRef` for mutable values that shouldn't trigger re-renders.\n- Use `useReducer` for complex state logic.\n\n**Node.js \u002F SSR Behavior:**\nHooks that rely on browser APIs (like `useEffect`) don't run on the server. They run after hydration on client.\n\n**Latest React Patterns:**\n- React 18 introduced `useId`, `useTransition`, `useDeferredValue`, `useSyncExternalStore`.\n- `useOptimistic` and `useFormStatus` for Server Components.\n\n**TypeScript Example:**\n```tsx\nconst [count, setCount] = useState\u003Cnumber>(0);\nconst nameRef = useRef\u003CHTMLInputElement>(null);\nconst { data } = useQuery\u003CUser>(['user'], fetchUser);\n```\n\n**Interview Tip:**\nExplain that hooks provide a direct API to React concepts without the complexity of classes (`this`, bindings, lifecycle confusion). Emphasize that custom hooks enable reusable logic.\n\n**Common Follow-up:**\n\"Can you use hooks in class components?\" (No)\n\n**Real-world Example:**\nA data-fetching custom hook (`useFetch`) that can be reused across many components, each with its own URL and caching logic.\n\n**Advanced Notes:**\nReact internally uses a `currentDispatcher` to track hooks. The order of hook calls determines which state gets returned. This is why conditional hooks are not allowed; they would shift the order.",[47,143,46,88],"rules-of-hooks",{"id":145,"category":7,"question":146,"answer":147,"level":10,"tags":148},18,"What is the difference between functional components and class components? When would you use each?","**Concept Explanation:**\nFunctional components are plain JavaScript functions that return JSX. Class components extend `React.Component` and have a `render` method. With hooks, functional components can do everything class components can, with less boilerplate. Class components are still used for error boundaries (React 16) and some legacy codebases.\n\n**Syntax Comparison:**\n```jsx\n\u002F\u002F Functional component\nfunction Welcome({ name }) {\n  const [count, setCount] = useState(0);\n  useEffect(() => {}, []);\n  return \u003Ch1>Hello {name}\u003C\u002Fh1>;\n}\n\n\u002F\u002F Class component\nclass Welcome extends React.Component {\n  state = { count: 0 };\n  componentDidMount() {}\n  render() { return \u003Ch1>Hello {this.props.name}\u003C\u002Fh1>; }\n}\n```\n\n**Code Example with State and Lifecycle:**\n```jsx\n\u002F\u002F Functional – modern\nfunction Timer() {\n  const [seconds, setSeconds] = useState(0);\n  \n  useEffect(() => {\n    const interval = setInterval(() => setSeconds(s => s + 1), 1000);\n    return () => clearInterval(interval);\n  }, []);\n  \n  return \u003Cdiv>{seconds}\u003C\u002Fdiv>;\n}\n\n\u002F\u002F Class – legacy\nclass Timer extends React.Component {\n  state = { seconds: 0 };\n  interval = null;\n  \n  componentDidMount() {\n    this.interval = setInterval(() => {\n      this.setState(prev => ({ seconds: prev.seconds + 1 }));\n    }, 1000);\n  }\n  \n  componentWillUnmount() {\n    clearInterval(this.interval);\n  }\n  \n  render() {\n    return \u003Cdiv>{this.state.seconds}\u003C\u002Fdiv>;\n  }\n}\n```\n\n**Execution Flow:**\n- **Functional:** Component function invoked on each render. Hooks manage state across calls.\n- **Class:** Component instance created, `render` called on each update, lifecycle methods invoked.\n\n**Reactivity Explanation:**\nBoth become reactive via setState\u002FuseState. Functional components capture props and state in closures; class components use `this.props`\u002F`this.state` which are mutable.\n\n**Practical Usage:**\n- **Functional:** All new components.\n- **Class:** Error boundaries (still need `componentDidCatch`, though hooks may add it in future).\n\n**Common Mistakes:**\n- In class components, forgetting to bind event handlers.\n- In functional components, causing infinite loops due to missing `useEffect` dependencies.\n\n**Interview Follow-ups:**\n- Can functional components have lifecycle methods? (No, but `useEffect` covers them)\n- Do functional components have `this`? (No)\n- What is the performance difference? (Negligible)\n\n**Best Practices:**\n- Always use functional components with hooks.\n- Only use class components if you must implement `componentDidCatch`.\n- Convert legacy class components gradually.\n\n**Performance Considerations:**\n- Functional components have slightly less overhead (no instance creation).\n- Both perform similarly in production.\n\n**Production Recommendations:**\n- Use functional components with React.memo for optimization.\n- Use `useCallback` and `useMemo` instead of class `shouldComponentUpdate`.\n\n**Node.js \u002F SSR Behavior:**\nBoth work. Lifecycle methods (`componentDidMount`) and `useEffect` don't run on server.\n\n**Latest React Patterns:**\n- React Server Components are functional and async (no hooks).\n- Error boundary support for functional components is not yet stable.\n\n**TypeScript Example:**\n```tsx\n\u002F\u002F Functional\nconst Button: React.FC\u003C{ onClick: () => void }> = ({ onClick }) => \u003Cbutton onClick={onClick}>Click\u003C\u002Fbutton>;\n\n\u002F\u002F Class\nclass Button extends React.Component\u003C{ onClick: () => void }> {\n  render() { return \u003Cbutton onClick={this.props.onClick}>Click\u003C\u002Fbutton>; }\n}\n```\n\n**Interview Tip:**\nState that hooks make functional components superior for almost all use cases. Mention error boundaries as the only exception (React 18 may change this).\n\n**Common Follow-up:**\n\"How do you implement `componentDidCatch` in a functional component?\" (You can't yet; use a class component for error boundaries)\n\n**Real-world Example:**\nA large React codebase migrating from classes to functions: they'd update state to hooks, replace lifecycle with useEffect, and remove `this` binding.\n\n**Advanced Notes:**\nClass components have a different rendering lifecycle (e.g., `componentWillReceiveProps` deprecated). Functional components with hooks offer more flexibility (custom hooks, better reusability). React team recommends functional components moving forward.",[28,29,30,149],"comparison",{"id":151,"category":84,"question":152,"answer":153,"level":10,"tags":154},19,"What is the useRef hook? How is it different from state and when would you use it?","**Concept Explanation:**\n`useRef` returns a mutable object with a `current` property that persists across renders without causing re-renders when changed. Unlike state, updating `ref.current` does not trigger a re-render. Common uses: accessing DOM elements directly, storing previous values, and keeping mutable instance variables.\n\n**Syntax Explanation:**\n```jsx\nconst refContainer = useRef(initialValue);\n\u002F\u002F Access: refContainer.current\n\u002F\u002F Update: refContainer.current = newValue (no re-render)\n```\n\n**Code Example:**\n```jsx\nfunction TextInputWithFocus() {\n  const inputRef = useRef(null);\n\n  const focusInput = () => {\n    inputRef.current.focus(); \u002F\u002F Direct DOM access\n  };\n\n  return (\n    \u003C>\n      \u003Cinput ref={inputRef} type=\"text\" \u002F>\n      \u003Cbutton onClick={focusInput}>Focus\u003C\u002Fbutton>\n    \u003C\u002F>\n  );\n}\n\n\u002F\u002F Storing previous value\nfunction Counter() {\n  const [count, setCount] = useState(0);\n  const prevCountRef = useRef();\n\n  useEffect(() => {\n    prevCountRef.current = count; \u002F\u002F Store after render\n  }, [count]);\n\n  const prevCount = prevCountRef.current;\n  return \u003Cdiv>Now: {count}, Before: {prevCount}\u003C\u002Fdiv>;\n}\n\n\u002F\u002F Mutable instance variable (like class instance property)\nfunction Timer() {\n  const intervalRef = useRef(null);\n\n  const startTimer = () => {\n    if (intervalRef.current) return;\n    intervalRef.current = setInterval(() => console.log('tick'), 1000);\n  };\n\n  const stopTimer = () => {\n    clearInterval(intervalRef.current);\n    intervalRef.current = null;\n  };\n\n  useEffect(() => stopTimer, []); \u002F\u002F cleanup\n\n  return (\n    \u003C>\n      \u003Cbutton onClick={startTimer}>Start\u003C\u002Fbutton>\n      \u003Cbutton onClick={stopTimer}>Stop\u003C\u002Fbutton>\n    \u003C\u002F>\n  );\n}\n```\n\n**Execution Flow:**\n- `useRef` creates an object `{ current: initialValue }`.\n- React stores this object in the component's fiber node.\n- On subsequent renders, the same object is returned.\n- Mutating `current` does not trigger a re-render.\n\n**Reactivity Explanation:**\n`useRef` is not reactive in the sense that changes don't cause UI updates. It's for data that should persist but not affect rendering.\n\n**Practical Usage:**\n- Accessing DOM elements (focus, measure, scroll).\n- Storing previous state\u002Fprops values.\n- Keeping references to timers, intervals, or subscriptions.\n- Avoiding stale closure issues (if you need mutable value across renders).\n\n**Common Mistakes:**\n- Using `useRef` when state is needed (thinking it will cause re-render).\n- Reading `ref.current` before it's assigned (e.g., before component mounts).\n- Using `ref.current` inside render for values that should update UI (should use state).\n\n**Interview Follow-ups:**\n- What is the difference between `useRef` and `createRef`?\n- Can you use `useRef` to trigger re-renders? (No, use state instead)\n- How do you measure DOM element dimensions with `useRef`?\n\n**Best Practices:**\n- Use `useRef` for DOM references and mutable instance variables.\n- Use state for values that should appear in UI.\n- In cleanup functions, clear ref-stored timers.\n\n**Performance Considerations:**\n- `useRef` has no performance penalty; it's just a mutable object.\n- Avoid reading `ref.current` repeatedly in render (but it's fine).\n\n**Production Recommendations:**\n- Use `useRef` to integrate with third-party DOM libraries.\n- Use refs to focus inputs on form errors.\n\n**Node.js \u002F SSR Behavior:**\n`useRef` works during SSR, but `ref.current` will be `null` because there is no DOM. It will be populated after hydration.\n\n**Latest React Patterns:**\n- `useRef` can be used with `forwardRef` to expose refs to parent components.\n- `useImperativeHandle` customizes the ref value exposed.\n\n**TypeScript Example:**\n```tsx\nconst inputRef = useRef\u003CHTMLInputElement>(null);\nconst intervalRef = useRef\u003CNodeJS.Timeout | null>(null);\n```\n\n**Interview Tip:**\nCompare `useRef` to instance variables in class components (`this.interval`). Explain that it's for mutable data that doesn't affect rendering.\n\n**Common Follow-up:**\n\"How would you implement focus on mount using `useRef`?\" (useEffect with ref.current?.focus())\n\n**Real-world Example:**\nA search input that automatically focuses when the page loads, and a \"clear\" button that clears the input and focuses it again.\n\n**Advanced Notes:**\n`useRef` can also be used to create forwardRefs. React also has `useImperativeHandle` to limit what ref exposes. Unlike `createRef` (which creates a new ref each render), `useRef` returns the same ref object across renders.",[155,156,157,47],"useRef","refs","dom",{"id":159,"category":74,"question":160,"answer":161,"level":10,"tags":162},20,"How do you handle form validation in React? Compare controlled approach with libraries like Formik and React Hook Form.","**Concept Explanation:**\nForm validation in React can be done manually (controlled components with state and validation logic) or using libraries like Formik (declarative) or React Hook Form (performant, uncontrolled). Manual validation gives fine control but can be verbose; libraries provide built-in validation, error handling, and performance optimizations.\n\n**Syntax Explanation:**\n```jsx\n\u002F\u002F Manual validation\nfunction LoginForm() {\n  const [email, setEmail] = useState('');\n  const [errors, setErrors] = useState({});\n  \n  const validate = () => {\n    const newErrors = {};\n    if (!email.includes('@')) newErrors.email = 'Invalid email';\n    setErrors(newErrors);\n    return Object.keys(newErrors).length === 0;\n  };\n  \n  const handleSubmit = (e) => {\n    e.preventDefault();\n    if (validate()) submit();\n  };\n}\n```\n\n**Code Example with React Hook Form:**\n```jsx\nimport { useForm } from 'react-hook-form';\nimport { zodResolver } from '@hookform\u002Fresolvers\u002Fzod';\nimport { z } from 'zod';\n\n\u002F\u002F Schema validation\nconst schema = z.object({\n  email: z.string().email('Invalid email'),\n  password: z.string().min(6, 'Password too short'),\n});\n\nfunction LoginForm() {\n  const { register, handleSubmit, formState: { errors, isSubmitting } } = useForm({\n    resolver: zodResolver(schema),\n  });\n\n  const onSubmit = (data) => console.log(data);\n\n  return (\n    \u003Cform onSubmit={handleSubmit(onSubmit)}>\n      \u003Cinput {...register('email')} \u002F>\n      {errors.email && \u003Cspan>{errors.email.message}\u003C\u002Fspan>}\n      \n      \u003Cinput {...register('password')} type=\"password\" \u002F>\n      {errors.password && \u003Cspan>{errors.password.message}\u003C\u002Fspan>}\n      \n      \u003Cbutton disabled={isSubmitting} type=\"submit\">Login\u003C\u002Fbutton>\n    \u003C\u002Fform>\n  );\n}\n```\n\n**Code Example with Formik (manual validation):**\n```jsx\nimport { Formik, Form, Field, ErrorMessage } from 'formik';\n\nconst validate = (values) => {\n  const errors = {};\n  if (!values.email) errors.email = 'Required';\n  else if (!\u002F\\S+@\\S+\\.\\S+\u002F.test(values.email)) errors.email = 'Invalid';\n  return errors;\n};\n\nfunction LoginForm() {\n  return (\n    \u003CFormik initialValues={{ email: '', password: '' }} validate={validate} onSubmit={console.log}>\n      \u003CForm>\n        \u003CField name=\"email\" \u002F>\n        \u003CErrorMessage name=\"email\" component=\"div\" \u002F>\n        \u003Cbutton type=\"submit\">Submit\u003C\u002Fbutton>\n      \u003C\u002FForm>\n    \u003C\u002FFormik>\n  );\n}\n```\n\n**Execution Flow:**\n- **Manual:** on every input change, run validation, set error state, re-render.\n- **React Hook Form:** uncontrolled inputs, validation on submit or on blur, minimizes re-renders.\n- **Formik:** controlled by default, re-renders on every keystroke.\n\n**Reactivity Explanation:**\nManual and Formik (controlled) cause re-renders on each input change. React Hook Form uses refs (uncontrolled) and only re-renders when needed.\n\n**Practical Usage:**\n- **Manual:** simple forms, learning purposes.\n- **React Hook Form:** large forms, performance-critical, TypeScript-friendly.\n- **Formik:** good for controlled forms with complex validation.\n\n**Common Mistakes:**\n- Not handling async validation properly.\n- Re-running validation on every keystroke causing lag.\n- Forgetting to disable submit button during submission.\n\n**Interview Follow-ups:**\n- How do you handle async validation (e.g., email uniqueness)?\n- What are the performance benefits of React Hook Form?\n- How do you integrate Yup\u002FZod with form libraries?\n\n**Best Practices:**\n- Use schema validation (Zod, Yup) for complex rules.\n- Use React Hook Form for production.\n- Display errors inline or via summary.\n\n**Performance Considerations:**\n- React Hook Form minimizes re-renders (only fields that change update).\n- Formik with `enableReinitialize` can cause extra renders.\n\n**Production Recommendations:**\n- Use React Hook Form with Zod resolver.\n- Add debounced async validation for unique fields.\n- Use `setError` API for server validation errors.\n\n**Node.js \u002F SSR Behavior:**\nReact Hook Form supports SSR; Formik also works but requires careful hydration.\n\n**Latest React Patterns:**\n- React 19 introduces `useFormStatus`, `useFormState` for Server Actions.\n- React Hook Form v7+ has better TypeScript support.\n\n**TypeScript Example:**\n```tsx\ninterface FormValues {\n  email: string;\n  password: string;\n}\n\nconst { register } = useForm\u003CFormValues>();\n```\n\n**Interview Tip:**\nExplain that manual validation gives control but becomes complex quickly. Libraries reduce boilerplate and provide accessibility features.\n\n**Common Follow-up:**\n\"How do you handle cross-field validation?\" (Use validate function with all values)\n\n**Real-world Example:**\nA checkout form with 10+ fields, async address validation, and dependent fields (country\u002Fcity). React Hook Form with Zod provides structured, performant validation.\n\n**Advanced Notes:**\nReact Hook Form's `mode` prop controls when validation runs (`onChange`, `onBlur`, `onSubmit`, `onTouched`). It also supports field arrays and nested objects.",[78,163,164,165],"validation","react-hook-form","formik",{"id":167,"category":7,"question":168,"answer":169,"level":10,"tags":170},21,"What is the children prop in React? How do you use it for composition?","**Concept Explanation:**\n`children` is a special prop that represents the content between the opening and closing tags of a component. It allows component composition, enabling wrapper components (like Card, Modal, Layout) to render arbitrary content.\n\n**Syntax Explanation:**\n```jsx\n\u002F\u002F Component that uses children\nfunction Card({ children, title }) {\n  return (\n    \u003Cdiv className=\"card\">\n      \u003Ch2>{title}\u003C\u002Fh2>\n      \u003Cdiv className=\"content\">{children}\u003C\u002Fdiv>\n    \u003C\u002Fdiv>\n  );\n}\n\n\u002F\u002F Usage\n\u003CCard title=\"Welcome\">\n  \u003Cp>This content is passed as children\u003C\u002Fp>\n  \u003Cbutton>Click\u003C\u002Fbutton>\n\u003C\u002FCard>\n```\n\n**Code Example:**\n```jsx\n\u002F\u002F Layout component\nfunction Layout({ children, sidebar }) {\n  return (\n    \u003Cdiv className=\"layout\">\n      \u003Caside>{sidebar}\u003C\u002Faside>\n      \u003Cmain>{children}\u003C\u002Fmain>\n    \u003C\u002Fdiv>\n  );\n}\n\n\u002F\u002F Usage with multiple children\nfunction App() {\n  return (\n    \u003CLayout sidebar={\u003CNav \u002F>}>\n      \u003Ch1>Main Content\u003C\u002Fh1>\n      \u003Cp>This goes to main\u003C\u002Fp>\n    \u003C\u002FLayout>\n  );\n}\n\n\u002F\u002F Children as function (render prop)\nfunction DataFetcher({ url, children }) {\n  const [data, setData] = useState(null);\n  useEffect(() => {\n    fetch(url).then(res => res.json()).then(setData);\n  }, [url]);\n  return children(data);\n}\n\n\u002F\u002F Usage\n\u003CDataFetcher url=\"\u002Fapi\u002Fuser\">\n  {(data) => \u003Cdiv>{data?.name}\u003C\u002Fdiv>}\n\u003C\u002FDataFetcher>\n```\n\n**Execution Flow:**\nWhen JSX is compiled, the nested content becomes the `children` prop. React handles `children` like any other prop, but it can be a primitive, an element, an array, or a function.\n\n**Reactivity Explanation:**\nIf `children` is a function (render prop), it re-runs when parent state changes. If `children` are React elements, they update based on their own props\u002Fstate.\n\n**Practical Usage:**\n- Creating reusable wrappers (modals, cards, tabs).\n- Layout components (headers, footers).\n- Render props pattern (sharing logic).\n\n**Common Mistakes:**\n- Forgetting to render `children` in the component.\n- Passing multiple children without wrapping in fragment (works, but keys may be needed).\n- Using `children` for data that should be props.\n\n**Interview Follow-ups:**\n- What is the difference between `children` and passing component as prop?\n- How do you type `children` in TypeScript?\n- Can you have multiple named children? (Yes, pass as props)\n\n**Best Practices:**\n- Use `children` for primary content that the parent doesn't need to inspect.\n- Use named props for multiple \"slots\" (e.g., `header`, `footer`).\n- Use `React.Children` utilities for manipulating children.\n\n**Performance Considerations:**\n- Passing new JSX as children each render causes child components to re-render. Use `React.memo` or lift content up if needed.\n\n**Production Recommendations:**\n- Use TypeScript to type `children: React.ReactNode`.\n- Use composition over prop drilling.\n\n**Node.js \u002F SSR Behavior:**\n`children` are serialized during SSR; function children are not serialized.\n\n**Latest React Patterns:**\n- Compound components often use `children` with `React.cloneElement`.\n- React 18 allows `children` to be a promise (Server Components).\n\n**TypeScript Example:**\n```tsx\ninterface CardProps {\n  children: React.ReactNode;\n  title?: string;\n}\n\nconst Card: React.FC\u003CCardProps> = ({ children, title }) => (\n  \u003Cdiv>\n    {title && \u003Ch2>{title}\u003C\u002Fh2>}\n    {children}\n  \u003C\u002Fdiv>\n);\n```\n\n**Interview Tip:**\nExplain that `children` enables the compositional model of React, similar to HTML elements nesting content.\n\n**Common Follow-up:**\n\"How do you pass props to children dynamically?\" (Use `React.cloneElement` or context)\n\n**Real-world Example:**\nA `Modal` component that accepts children (any content) and a `footer` prop for buttons. This keeps the component flexible and reusable.\n\n**Advanced Notes:**\n`React.Children.map`, `React.Children.toArray` help work with children when you need to add props or modify them. `React.cloneElement` can be used to inject props into child components.",[171,172,36],"children","composition",{"id":174,"category":175,"question":176,"answer":177,"level":10,"tags":178},22,"Performance Optimization","What is React DevTools and how can you use it for debugging and performance profiling?","**Concept Explanation:**\nReact DevTools is a browser extension for debugging React applications. It provides components tree inspection, props\u002Fstate viewing, component highlighting, and performance profiling tools. The Profiler records rendering times, identifies inefficient components, and shows why components re-rendered.\n\n**Syntax Explanation:**\n(No code – DevTools is a browser extension)\n\n**Key Features:**\n- **Components tab:** Inspect component hierarchy, view props, state, and hooks.\n- **Profiler tab:** Record interactions, measure render duration, identify slow components.\n- **Highlight updates:** Visualize when components re-render.\n- **Suspense and Context debugging.**\n\n**Usage Example (Profiling):**\n1. Open DevTools → React tab → Profiler.\n2. Click record (circle button).\n3. Interact with app.\n4. Stop recording.\n5. View flame graph (render times) and ranked list (slowest components).\n6. Click on a component to see why it rendered (props\u002Fstate changes).\n\n**Practical Usage:**\n- Finding unnecessary re-renders.\n- Measuring impact of memoization.\n- Debugging state\u002Fprop issues.\n- Verifying that optimization works.\n\n**Common Mistakes:**\n- Not using the profiler for performance work (guessing instead of measuring).\n- Forgetting that production builds have different performance characteristics.\n- Overlooking the \"why did this render\" information.\n\n**Interview Follow-ups:**\n- How do you profile a React app for performance issues?\n- What does the `⚛️` highlight mean in DevTools?\n- Can you debug remote React apps?\n\n**Best Practices:**\n- Use DevTools in development with the extension.\n- Use the Profiler for before\u002Fafter optimization comparisons.\n- Install `react-devtools` standalone for debugging non-browser environments.\n\n**Performance Considerations:**\n- DevTools itself adds overhead; always measure with production builds for accurate results.\n- Use `\u003CReact.Profiler>` component to collect data in production (opt-in).\n\n**Production Recommendations:**\n- You can use `react-devtools` with React Native.\n- Use `useWhyDidYouRender` custom hook for deeper analysis.\n- In production, you can use the `react-devtools` standalone.\n\n**Node.js \u002F SSR Behavior:**\nDevTools works with server-side rendering debugging (components tree, but interactions are client-only).\n\n**Latest React Patterns:**\n- React 18 Profiler supports concurrent rendering profiling.\n- Use Timeline mode for performance analysis.\n\n**TypeScript Example:**\n(Not applicable)\n\n**Interview Tip:**\nExplain that DevTools is essential for debugging and optimizing React apps. Mention that the Profiler helps identify expensive components and unnecessary re-renders.\n\n**Common Follow-up:**\n\"What is the `react-devtools` package?\" (Standalone version for mobile\u002Fiframe debugging)\n\n**Real-world Example:**\nA slow list component – using DevTools Profiler reveals that every item re-renders on each keystroke. The solution: memoize list items with `React.memo` and stable keys.\n\n**Advanced Notes:**\n`React DevTools` also supports inspecting Suspense boundaries, Context providers, and hooks (including custom hook values). The `Components` tab can edit state and props for quick testing.",[179,180,181,182],"devtools","debugging","profiling","performance",{"id":184,"category":109,"question":185,"answer":186,"level":10,"tags":187},23,"How do you handle loading and error states when fetching data in React?","**Concept Explanation:**\nWhen fetching data asynchronously, you need to manage three states: loading (request in progress), success (data received), and error (request failed). These states should be reflected in the UI to provide feedback to users (e.g., loading spinners, error messages).\n\n**Syntax Explanation:**\n```jsx\nfunction DataComponent() {\n  const [data, setData] = useState(null);\n  const [loading, setLoading] = useState(true);\n  const [error, setError] = useState(null);\n\n  useEffect(() => {\n    fetchData()\n      .then(setData)\n      .catch(setError)\n      .finally(() => setLoading(false));\n  }, []);\n\n  if (loading) return \u003CSpinner \u002F>;\n  if (error) return \u003CErrorMessage error={error} \u002F>;\n  return \u003CDisplay data={data} \u002F>;\n}\n```\n\n**Code Example with React Query:**\n```jsx\nimport { useQuery, useMutation } from '@tanstack\u002Freact-query';\n\nfunction UserProfile({ userId }) {\n  const { data, isLoading, error, isError, refetch } = useQuery({\n    queryKey: ['user', userId],\n    queryFn: () => fetch(`\u002Fapi\u002Fusers\u002F${userId}`).then(res => res.json()),\n    retry: 3,\n    staleTime: 5000,\n  });\n\n  if (isLoading) return (\n    \u003Cdiv className=\"flex justify-center\">\n      \u003CSpinner \u002F>\n      \u003Cspan>Loading user data...\u003C\u002Fspan>\n    \u003C\u002Fdiv>\n  );\n\n  if (isError) return (\n    \u003Cdiv className=\"error-container\">\n      \u003Cp>Failed to load user: {error.message}\u003C\u002Fp>\n      \u003Cbutton onClick={() => refetch()}>Retry\u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  );\n\n  return \u003Cdiv>{data.name}\u003C\u002Fdiv>;\n}\n\n\u002F\u002F Mutation with loading\u002Ferror\nfunction AddComment({ postId }) {\n  const [localError, setLocalError] = useState(null);\n  const mutation = useMutation({\n    mutationFn: (comment) => fetch(`\u002Fapi\u002Fposts\u002F${postId}\u002Fcomments`, { method: 'POST', body: JSON.stringify(comment) }),\n    onError: (err) => setLocalError(err),\n    onSuccess: () => setLocalError(null),\n  });\n\n  return (\n    \u003Cdiv>\n      \u003Cbutton onClick={() => mutation.mutate({ text: 'Great post!' })} disabled={mutation.isPending}>\n        {mutation.isPending ? 'Adding...' : 'Add Comment'}\n      \u003C\u002Fbutton>\n      {mutation.isError && \u003Cspan>Error: {mutation.error.message}\u003C\u002Fspan>}\n      {mutation.isSuccess && \u003Cspan>Comment added!\u003C\u002Fspan>}\n    \u003C\u002Fdiv>\n  );\n}\n```\n\n**Execution Flow:**\n1. Component mounts, `loading` = true.\n2. Fetch request starts.\n3. If request succeeds, set data and loading=false.\n4. If request fails, set error and loading=false.\n5. UI updates accordingly.\n\n**Reactivity Explanation:**\nLoading\u002Ferror states are reactive – when state changes, the component re-renders to show appropriate UI.\n\n**Practical Usage:**\n- Show loading skeletons or spinners.\n- Display user-friendly error messages with retry options.\n- Disable form submission during mutation.\n\n**Common Mistakes:**\n- Not handling error state at all (app may crash).\n- Forgetting to clean up (set isMounted flag) to prevent state updates on unmounted components.\n- Showing loading state indefinitely if promise never resolves (add timeout).\n\n**Interview Follow-ups:**\n- How do you prevent race conditions in data fetching?\n- How do you handle global loading indicators?\n- What is the difference between error boundary and inline error handling?\n\n**Best Practices:**\n- Use React Query or SWR to abstract loading\u002Ferror states.\n- Provide retry mechanism for transient errors.\n- Use skeleton loaders for better UX.\n- Show error boundaries for catastrophic errors.\n\n**Performance Considerations:**\n- Avoid multiple loading spinners causing layout shifts – use consistent skeleton placeholders.\n- React Query deduplicates requests and caches results.\n\n**Production Recommendations:**\n- Use `react-error-boundary` library.\n- Log errors to monitoring service (Sentry, LogRocket).\n- Implement exponential backoff for retries.\n\n**Node.js \u002F SSR Behavior:**\nOn server, there's no loading state (data is fetched before rendering). On hydration, the client may show loading initially if data isn't available.\n\n**Latest React Patterns:**\n- React 18 Suspense for data fetching (with libraries like Relay, Next.js).\n- `useTransition` for loading UI.\n\n**TypeScript Example:**\n```tsx\ninterface DataState\u003CT> {\n  status: 'idle' | 'loading' | 'success' | 'error';\n  data: T | null;\n  error: Error | null;\n}\n\nconst [state, setState] = useState\u003CDataState\u003CUser>>({ status: 'idle', data: null, error: null });\n```\n\n**Interview Tip:**\nExplain that loading and error states are fundamental to a good user experience. Mention that modern libraries like React Query automate most of this boilerplate.\n\n**Common Follow-up:**\n\"How do you show a loading indicator only after a delay (to avoid flashing for fast requests)?\" (Use `startTransition` or `useDeferredValue` or delay setting loading state)\n\n**Real-world Example:**\nA search input that fetches results: show loading spinner only if fetch takes longer than 300ms. Use a debounced loading state.\n\n**Advanced Notes:**\nConsider using `AbortController` to cancel in-flight requests when new request arrives. React Query does this automatically. For global error handling, use error boundaries with `componentDidCatch` or `react-error-boundary`.",[113,188,189,114],"loading-states","error-handling",{"id":191,"category":7,"question":192,"answer":193,"level":10,"tags":194},24,"How do you create a basic React project? Explain the folder structure and build process.","**Concept Explanation:**\nThe most common way to start a React project is using a build tool like Vite, Create React App (CRA), or Next.js. These tools set up a development server, build process, and optimizations. Modern React (2024+) recommends Vite or Next.js for new projects, as CRA is deprecated.\n\n**Command Examples:**\n```bash\n# Vite (recommended for SPA)\nnpm create vite@latest my-app -- --template react\nyarn create vite my-app --template react\n\n# Next.js (full-stack framework)\nnpx create-next-app@latest my-app\n\n# Create React App (deprecated, not recommended)\nnpx create-react-app my-app\n\n# Install dependencies\ncd my-app\nnpm install\nnpm run dev  # Vite dev server\nnpm run build  # production build\n```\n\n**Folder Structure (Vite + React):**\n```\nmy-app\u002F\n├── public\u002F              # Static assets (favicon, robots.txt)\n├── src\u002F\n│   ├── assets\u002F          # Images, fonts, etc.\n│   ├── components\u002F      # Reusable components\n│   │   ├── Button\u002F\n│   │   │   ├── Button.jsx\n│   │   │   └── Button.module.css\n│   ├── pages\u002F           # Page components (if using routing)\n│   ├── hooks\u002F           # Custom hooks\n│   ├── utils\u002F           # Helper functions\n│   ├── App.jsx          # Root component\n│   ├── main.jsx         # Entry point\n│   └── index.css        # Global styles\n├── index.html           # HTML template\n├── package.json         # Dependencies and scripts\n├── vite.config.js       # Vite configuration\n└── .gitignore\n```\n\n**Build Process:**\n1. `npm run dev` starts development server with Hot Module Replacement (HMR).\n2. `npm run build` bundles and optimizes:\n   - JSX\u002FTypeScript compilation via esbuild (Vite) or Babel (CRA).\n   - Minification (Terser\u002Fesbuild).\n   - Code splitting (dynamic imports).\n   - Asset optimization (images, CSS).\n3. Output is placed in `dist\u002F` or `build\u002F`.\n4. Deploy that folder to a static hosting service (Netlify, Vercel, AWS S3).\n\n**Key Files:**\n```jsx\n\u002F\u002F src\u002Fmain.jsx (entry point)\nimport React from 'react';\nimport ReactDOM from 'react-dom\u002Fclient';\nimport App from '.\u002FApp';\nimport '.\u002Findex.css';\n\nReactDOM.createRoot(document.getElementById('root')).render(\n  \u003CReact.StrictMode>\n    \u003CApp \u002F>\n  \u003C\u002FReact.StrictMode>\n);\n\n\u002F\u002F src\u002FApp.jsx\nfunction App() {\n  return \u003Ch1>Hello React\u003C\u002Fh1>;\n}\n\nexport default App;\n```\n\n**Practical Usage:**\n- Choose Vite for SPAs, PWAs, and libraries.\n- Choose Next.js for SSR, SSG, or API routes.\n- Avoid Create React App for new projects.\n\n**Common Mistakes:**\n- Using CRA for new projects (deprecated, slow).\n- Not understanding build vs development environment.\n- Putting sensitive data in frontend bundles (API keys).\n\n**Interview Follow-ups:**\n- What is the difference between development and production builds?\n- How does Vite differ from Webpack?\n- What is the purpose of `StrictMode`?\n\n**Best Practices:**\n- Use environment variables for configuration (`import.meta.env.VITE_API_URL` in Vite).\n- Organize components by feature or type.\n- Use absolute imports via `jsconfig.json`.\n\n**Performance Considerations:**\n- Vite uses esbuild (Go) for fast builds.\n- Production builds include minification and tree shaking.\n- Code splitting can be configured via dynamic imports.\n\n**Production Recommendations:**\n- Use Vite with `@vitejs\u002Fplugin-react`.\n- Add `eslint` and `prettier` for code quality.\n- Set up `husky` for pre-commit hooks.\n- Configure environment-specific builds.\n\n**Node.js \u002F SSR Behavior:**\n- Vite supports SSR via `@vitejs\u002Fplugin-react` with Node.js.\n- Next.js handles SSR out of the box.\n\n**Latest React Patterns:**\n- React 19 may include a first-party build tool (React Compiler).\n- Vite is the industry standard for SPAs.\n\n**TypeScript Example:**\n```bash\nnpm create vite@latest my-app -- --template react-ts\n```\n\n**Interview Tip:**\nShow you're up-to-date by recommending Vite over CRA. Explain that modern build tools offer faster HMR and optimized bundling.\n\n**Common Follow-up:**\n\"How do you add TypeScript to an existing React project?\" (Rename .js to .tsx, install types, configure tsconfig.json)\n\n**Real-world Example:**\nA team migrating from CRA to Vite reduces build time from 2 minutes to 10 seconds.\n\n**Advanced Notes:**\nVite uses `esbuild` for transpilation and `Rollup` for production bundling. The `index.html` is at the root, allowing direct script injection. `StrictMode` helps detect side effects and deprecated APIs.",[195,196,197,198],"setup","build-tools","vite","project-structure",{"id":200,"category":201,"question":202,"answer":203,"level":10,"tags":204},25,"TypeScript","What are the benefits of using TypeScript with React? Provide basic type definitions for components and hooks.","**Concept Explanation:**\nTypeScript adds static typing to React, catching errors at compile time instead of runtime. Benefits include: better IDE autocompletion, safer refactoring, documentation via types, and fewer runtime errors (e.g., props mistakes, null references).\n\n**Syntax Explanation:**\n```tsx\n\u002F\u002F Typing component props\ninterface ButtonProps {\n  label: string;\n  onClick: () => void;\n  disabled?: boolean; \u002F\u002F optional\n}\n\nconst Button: React.FC\u003CButtonProps> = ({ label, onClick, disabled = false }) => {\n  return \u003Cbutton onClick={onClick} disabled={disabled}>{label}\u003C\u002Fbutton>;\n};\n\n\u002F\u002F Typing state\nconst [count, setCount] = useState\u003Cnumber>(0);\nconst [user, setUser] = useState\u003CUser | null>(null);\n```\n\n**Code Example:**\n```tsx\n\u002F\u002F Typing props with children\ninterface CardProps {\n  title: string;\n  children: React.ReactNode;\n  onClose?: () => void;\n}\n\nconst Card: React.FC\u003CCardProps> = ({ title, children, onClose }) => {\n  return (\n    \u003Cdiv className=\"card\">\n      \u003Ch2>{title}\u003C\u002Fh2>\n      \u003Cdiv>{children}\u003C\u002Fdiv>\n      {onClose && \u003Cbutton onClick={onClose}>Close\u003C\u002Fbutton>}\n    \u003C\u002Fdiv>\n  );\n};\n\n\u002F\u002F Typing hooks\nfunction useLocalStorage\u003CT>(key: string, initialValue: T): [T, (value: T) => void] {\n  const [storedValue, setStoredValue] = useState\u003CT>(() => {\n    const item = window.localStorage.getItem(key);\n    return item ? JSON.parse(item) : initialValue;\n  });\n\n  const setValue = (value: T) => {\n    setStoredValue(value);\n    window.localStorage.setItem(key, JSON.stringify(value));\n  };\n\n  return [storedValue, setValue];\n}\n\n\u002F\u002F Usage\nconst [name, setName] = useLocalStorage\u003Cstring>('name', 'Guest');\n\n\u002F\u002F Typing event handlers\nconst handleChange = (e: React.ChangeEvent\u003CHTMLInputElement>) => {\n  setValue(e.target.value);\n};\n\nconst handleClick = (e: React.MouseEvent\u003CHTMLButtonElement>) => {\n  e.preventDefault();\n};\n\n\u002F\u002F Typing refs\nconst inputRef = useRef\u003CHTMLInputElement>(null);\n```\n\n**Practical Usage:**\n- Define interfaces for API responses.\n- Use union types for state variations (`type Status = 'idle' | 'loading' | 'success' | 'error'`).\n- Use generics for reusable hooks.\n\n**Common Mistakes:**\n- Using `any` frequently (disables type checking).\n- Not handling `null`\u002F`undefined` properly.\n- Overcomplicating types unnecessarily.\n\n**Interview Follow-ups:**\n- What is the difference between `interface` and `type` in TypeScript?\n- How do you type `useReducer`?\n- How do you handle generic components?\n\n**Best Practices:**\n- Prefer `interface` for object types, `type` for unions\u002Futility types.\n- Use `React.FC` or explicitly type `children` if needed.\n- Avoid using `any`; use `unknown` with type guards instead.\n\n**Performance Considerations:**\n- TypeScript compiles away, no runtime cost.\n- Better IDE performance with accurate types.\n\n**Production Recommendations:**\n- Enable `strict` mode in `tsconfig.json`.\n- Use `tsc --noEmit` in CI to check types.\n- Use `@types\u002Freact` and `@types\u002Freact-dom`.\n\n**Node.js \u002F SSR Behavior:**\nTypes are only development-time, no impact on runtime.\n\n**Latest React Patterns:**\n- React Server Components with TypeScript have full support.\n- `satisfies` operator for strict object literals.\n\n**TypeScript Example (Advanced):**\n```tsx\n\u002F\u002F Discriminated union for state\ninterface LoadingState { status: 'loading'; }\ninterface SuccessState\u003CT> { status: 'success'; data: T; }\ninterface ErrorState { status: 'error'; error: Error; }\ntype FetchState\u003CT> = LoadingState | SuccessState\u003CT> | ErrorState;\n\nfunction useFetch\u003CT>(url: string): FetchState\u003CT> {\n  const [state, setState] = useState\u003CFetchState\u003CT>>({ status: 'loading' });\n  \u002F\u002F ...\n}\n```\n\n**Interview Tip:**\nHighlight that TypeScript catches prop type mismatches before runtime, which is especially valuable in large teams and refactors.\n\n**Common Follow-up:**\n\"How do you type `React.forwardRef`?\" (Use generics: `React.forwardRef\u003CT, P>`)\n\n**Real-world Example:**\nA component library with TypeScript ensures that consumers get autocomplete and type errors when using the components incorrectly, reducing support tickets.\n\n**Advanced Notes:**\nTypeScript can infer most types from usage. Use `as const` for literal types. `React.PropsWithChildren` is a utility type. `React.ElementRef` extracts ref type from component.",[205,206,207,47],"typescript","typing","interfaces",[209,218,226,234,242,249,255,264,272,280,288,295,301,307,314,320,325,332,338,348],{"id":210,"category":84,"question":211,"answer":212,"level":213,"tags":214},26,"How does useEffect handle cleanup and dependencies? Explain the concept of stale closures and how to avoid them.","**Concept Explanation:**\n`useEffect` runs after render by default. It can return a cleanup function that runs before the next effect (to clean up previous subscriptions) and before unmount. The dependency array controls when the effect re-runs. Stale closures occur when an effect captures outdated props\u002Fstate because dependencies are missing or incorrect, causing the effect to use old values.\n\n**Syntax Explanation:**\n```jsx\nuseEffect(() => {\n  \u002F\u002F Setup \u002F side effect\n  const subscription = subscribe();\n\n  \u002F\u002F Cleanup – runs before next effect and on unmount\n  return () => {\n    subscription.unsubscribe();\n  };\n}, [dependency1, dependency2]); \u002F\u002F Re-run when dependencies change\n```\n\n**Code Example:**\n```jsx\nfunction Timer({ initialCount }) {\n  const [count, setCount] = useState(initialCount);\n\n  \u002F\u002F ❌ Stale closure – missing dependency\n  useEffect(() => {\n    const interval = setInterval(() => {\n      setCount(count + 1); \u002F\u002F count is stale from first render\n    }, 1000);\n    return () => clearInterval(interval);\n  }, []); \u002F\u002F Missing 'count' dependency\n\n  \u002F\u002F ✅ Correct – functional update avoids dependency\n  useEffect(() => {\n    const interval = setInterval(() => {\n      setCount(prev => prev + 1); \u002F\u002F No dependency on count needed\n    }, 1000);\n    return () => clearInterval(interval);\n  }, []);\n\n  \u002F\u002F ✅ Include dependency\n  useEffect(() => {\n    const interval = setInterval(() => {\n      setCount(count + 1);\n    }, 1000);\n    return () => clearInterval(interval);\n  }, [count]); \u002F\u002F Runs every time count changes\n\n  \u002F\u002F Cleanup demonstration\n  useEffect(() => {\n    console.log('Effect ran with count:', count);\n    return () => console.log('Cleaning up count:', count);\n  }, [count]);\n\n  return \u003Cdiv>{count}\u003C\u002Fdiv>;\n}\n```\n\n**Execution Flow:**\n1. Component renders with dependencies `[dep1, dep2]`.\n2. React compares previous and new dependency values using `Object.is`.\n3. If any changed, React runs the previous cleanup function (if any).\n4. Then runs the current effect.\n5. On unmount, runs the last cleanup.\n\n**Reactivity Explanation:**\nDependencies make the effect reactive to changes. Missing dependencies cause the effect to read stale values from the closure.\n\n**Practical Usage:**\n- Subscribing to external events (resize, scroll, WebSocket).\n- Setting up timers.\n- Fetching data (with dependencies like `userId`).\n\n**Common Mistakes:**\n- Empty dependency array but using props\u002Fstate inside effect (stale closure).\n- Forgetting cleanup leads to memory leaks.\n- Adding unnecessary dependencies (causes over-firing).\n- Not using functional updates when state depends on previous state.\n\n**Interview Follow-ups:**\n- What is a stale closure and why does it happen?\n- How does React compare dependencies?\n- What happens if you omit the dependency array?\n\n**Best Practices:**\n- Use `eslint-plugin-react-hooks` to enforce correct dependencies.\n- Prefer functional updates (`setCount(prev => prev+1)`) when new state depends on old.\n- Use `useCallback` and `useMemo` to stabilize dependencies.\n- Keep effects focused and minimal.\n\n**Performance Considerations:**\n- Too many dependencies can cause frequent effect re-runs.\n- Cleanup prevents memory leaks from accumulating listeners.\n\n**Production Recommendations:**\n- Use `useEffect` with abort controller for fetch cleanups.\n- Use `useRef` for values that should not trigger effect re-runs.\n\n**Node.js \u002F SSR Behavior:**\n`useEffect` never runs on server. Cleanup functions are not called on server.\n\n**Latest React Patterns:**\n- React 18's automatic batching affects timing but not the effect logic.\n- `useInsertionEffect` for CSS-in-JS, `useLayoutEffect` for synchronous DOM updates.\n\n**TypeScript Example:**\n```tsx\nuseEffect(() => {\n  const timer = setTimeout(() => console.log('Hello'), 1000);\n  return () => clearTimeout(timer);\n}, []);\n```\n\n**Interview Tip:**\nExplain that every function inside the effect captures the values from the render where it was created. Dependencies tell React when to \"refresh\" that closure.\n\n**Common Follow-up:**\n\"How do you handle an effect that should only run once, but depends on a value that changes?\" (Use the value in the effect but also in dependencies; or use a ref to track first run).\n\n**Real-world Example:**\nA chat component subscribes to a room. When `roomId` changes, cleanup previous subscription and subscribe to new room.\n\n**Advanced Notes:**\nReact will call cleanup before the next effect, even if the component is re-rendered due to unrelated state changes but dependencies unchanged (no cleanup). The cleanup also runs on unmount. Functional updates inside effects are safe because they don't need to include the state variable in dependencies.","intermediate",[88,215,216,217],"cleanup","stale-closures","dependencies",{"id":219,"category":84,"question":220,"answer":221,"level":213,"tags":222},27,"What are useMemo and useCallback? How do they optimize performance and when should you use them?","**Concept Explanation:**\n`useMemo` memoizes the result of a computation, recalculating only when dependencies change. `useCallback` memoizes a function reference, returning the same function instance unless dependencies change. Both prevent unnecessary recalculations and help child components avoid re-rendering when props haven't changed.\n\n**Syntax Explanation:**\n```jsx\n\u002F\u002F useMemo returns memoized value\nconst memoizedValue = useMemo(() => expensiveComputation(a, b), [a, b]);\n\n\u002F\u002F useCallback returns memoized function\nconst memoizedCallback = useCallback(() => doSomething(a, b), [a, b]);\n```\n\n**Code Example:**\n```jsx\nimport { useState, useMemo, useCallback } from 'react';\n\nfunction ProductList({ products, filterTerm }) {\n  \u002F\u002F Expensive filtering – only recompute when products or filterTerm change\n  const filteredProducts = useMemo(() => {\n    console.log('Filtering products...');\n    return products.filter(p => p.name.includes(filterTerm));\n  }, [products, filterTerm]);\n\n  \u002F\u002F Callback that depends on filteredProducts – memoized\n  const handleSelect = useCallback((productId) => {\n    console.log(`Selected product ${productId} from ${filteredProducts.length} items`);\n  }, [filteredProducts]); \u002F\u002F depends on memoized value\n\n  return (\n    \u003Cul>\n      {filteredProducts.map(p => (\n        \u003CProductItem key={p.id} product={p} onSelect={handleSelect} \u002F>\n      ))}\n    \u003C\u002Ful>\n  );\n}\n\n\u002F\u002F Child component memoized to avoid re-renders\nconst ProductItem = React.memo(({ product, onSelect }) => {\n  console.log(`Rendering ${product.name}`);\n  return \u003Cli onClick={() => onSelect(product.id)}>{product.name}\u003C\u002Fli>;\n});\n\n\u002F\u002F Without useCallback – ProductItem would re-render on every parent render\n\u002F\u002F because handleSelect would be a new function each time\n```\n\n**Execution Flow:**\n- `useMemo`: On render, if dependencies unchanged, returns cached value; otherwise runs function and caches result.\n- `useCallback`: On render, if dependencies unchanged, returns previous function reference; otherwise creates new function.\n\n**Reactivity Explanation:**\nBoth hooks make values reactive to dependency changes but avoid recomputation on every render.\n\n**Practical Usage:**\n- **useMemo:** Expensive calculations (sorting, filtering, data transformations).\n- **useCallback:** Passing callbacks to memoized child components (`React.memo`).\n- As dependencies for other hooks (e.g., `useEffect`).\n\n**Common Mistakes:**\n- Over-optimizing (using `useMemo` for trivial computations).\n- Omitting dependencies or including unnecessary ones.\n- Using `useCallback` without `React.memo` (no benefit).\n- Creating closures inside `useCallback` that access non-memoized values.\n\n**Interview Follow-ups:**\n- When is `useMemo` useless? (For primitive values or cheap computations)\n- What is the difference between `useCallback` and `useMemo`?\n- Can `useCallback` replace `useMemo`? (They serve different purposes)\n\n**Best Practices:**\n- Use `useMemo` for expensive computations (O(n) or more).\n- Use `useCallback` when passing callbacks to memoized children.\n- Profile before optimizing – don't prematurely add.\n- Follow ESLint `exhaustive-deps` rule.\n\n**Performance Considerations:**\n- `useMemo`\u002F`useCallback` themselves have overhead (storing and comparing dependencies).\n- Only beneficial if the computation is expensive or the function reference is passed down.\n\n**Production Recommendations:**\n- Use `useMemo` for derived state in large lists.\n- Use `useCallback` in component libraries where callbacks are passed to many children.\n- Combine with `React.memo` for optimal rendering.\n\n**Node.js \u002F SSR Behavior:**\nBoth hooks run during SSR but memoization only applies within a single render pass.\n\n**Latest React Patterns:**\n- React 18's `useTransition` and `useDeferredValue` can sometimes replace `useMemo` for UI responsiveness.\n- React Compiler (future) may auto-memoize, reducing manual usage.\n\n**TypeScript Example:**\n```tsx\nconst filtered = useMemo\u003CProduct[]>(() => {\n  return products.filter(p => p.name.includes(term));\n}, [products, term]);\n\nconst handleClick = useCallback((id: number) => {\n  console.log(id);\n}, []);\n```\n\n**Interview Tip:**\nExplain that `useCallback(fn, deps)` is equivalent to `useMemo(() => fn, deps)`. Emphasize that you should only use these when you have measured a performance problem.\n\n**Common Follow-up:**\n\"What happens if you use `useCallback` but the child is not memoized?\" (Child still re-renders, but parent may have some benefit if it avoids re-creating the function – minimal).\n\n**Real-world Example:**\nA data grid with 10,000 rows. Filtering without `useMemo` would recalculate on every keystroke, causing lag. With `useMemo`, filtering only runs when data or filter changes.\n\n**Advanced Notes:**\n`useMemo` does not guarantee that memoization will be preserved; React may discard cached values to free memory. Dependencies are compared with `Object.is`. For complex objects, consider using `useDeepCompareMemo` from libraries if needed.",[223,224,182,225],"useMemo","useCallback","memoization",{"id":227,"category":84,"question":228,"answer":229,"level":213,"tags":230},28,"How do you create custom hooks? Provide examples for data fetching and form handling.","**Concept Explanation:**\nCustom hooks are JavaScript functions that start with `use` and can call other hooks. They allow you to extract reusable logic (state, effects, context) from components, following the same rules as built-in hooks. They promote DRY principle and separation of concerns.\n\n**Syntax Explanation:**\n```jsx\n\u002F\u002F Custom hook naming convention: use[Something]\nfunction useCustomHook(initialValue) {\n  const [value, setValue] = useState(initialValue);\n  useEffect(() => { \u002F* logic *\u002F }, [value]);\n  return [value, setValue];\n}\n\n\u002F\u002F Usage in component\nconst [data, setData] = useCustomHook(0);\n```\n\n**Code Example:**\n```jsx\n\u002F\u002F 1. Data fetching hook\nfunction useFetch(url, options = {}) {\n  const [data, setData] = useState(null);\n  const [loading, setLoading] = useState(true);\n  const [error, setError] = useState(null);\n\n  useEffect(() => {\n    const abortController = new AbortController();\n    const fetchData = async () => {\n      setLoading(true);\n      try {\n        const response = await fetch(url, { ...options, signal: abortController.signal });\n        if (!response.ok) throw new Error(`HTTP ${response.status}`);\n        const result = await response.json();\n        setData(result);\n        setError(null);\n      } catch (err) {\n        if (err.name !== 'AbortError') setError(err);\n      } finally {\n        setLoading(false);\n      }\n    };\n    fetchData();\n    return () => abortController.abort();\n  }, [url, JSON.stringify(options)]);\n\n  return { data, loading, error };\n}\n\n\u002F\u002F 2. Form handling hook\nfunction useForm(initialValues, validate) {\n  const [values, setValues] = useState(initialValues);\n  const [errors, setErrors] = useState({});\n  const [touched, setTouched] = useState({});\n\n  const handleChange = (e) => {\n    const { name, value } = e.target;\n    setValues(prev => ({ ...prev, [name]: value }));\n    if (validate) {\n      const validationErrors = validate({ ...values, [name]: value });\n      setErrors(prev => ({ ...prev, [name]: validationErrors[name] }));\n    }\n  };\n\n  const handleBlur = (e) => {\n    const { name } = e.target;\n    setTouched(prev => ({ ...prev, [name]: true }));\n  };\n\n  const resetForm = () => {\n    setValues(initialValues);\n    setErrors({});\n    setTouched({});\n  };\n\n  return { values, errors, touched, handleChange, handleBlur, resetForm };\n}\n\n\u002F\u002F 3. useLocalStorage hook\nfunction useLocalStorage(key, initialValue) {\n  const [storedValue, setStoredValue] = useState(() => {\n    try {\n      const item = window.localStorage.getItem(key);\n      return item ? JSON.parse(item) : initialValue;\n    } catch {\n      return initialValue;\n    }\n  });\n\n  const setValue = (value) => {\n    try {\n      const valueToStore = value instanceof Function ? value(storedValue) : value;\n      setStoredValue(valueToStore);\n      window.localStorage.setItem(key, JSON.stringify(valueToStore));\n    } catch (error) {\n      console.error(error);\n    }\n  };\n\n  return [storedValue, setValue];\n}\n\n\u002F\u002F Usage in component\nfunction UserProfile({ userId }) {\n  const { data: user, loading, error } = useFetch(`\u002Fapi\u002Fusers\u002F${userId}`);\n  const { values, handleChange, resetForm } = useForm({ name: '', email: '' });\n  const [theme, setTheme] = useLocalStorage('theme', 'light');\n\n  if (loading) return \u003Cdiv>Loading...\u003C\u002Fdiv>;\n  if (error) return \u003Cdiv>Error: {error.message}\u003C\u002Fdiv>;\n\n  return \u003Cdiv>{user.name}\u003C\u002Fdiv>;\n}\n```\n\n**Execution Flow:**\nCustom hooks are called during component render. They run in the same order every time. React tracks hooks inside the custom function similarly to built-in hooks.\n\n**Reactivity Explanation:**\nAny state or effect inside a custom hook will cause the host component to re-render appropriately. The hook can return reactive values.\n\n**Practical Usage:**\n- Abstracting data fetching logic.\n- Managing form state and validation.\n- Subscribing to event listeners or WebSockets.\n- Persisting state to localStorage.\n- Handling debouncing or throttling.\n\n**Common Mistakes:**\n- Not starting hook names with `use` (ESLint will warn).\n- Calling hooks conditionally inside the custom hook.\n- Returning non-reactive values that cause stale closures.\n- Not cleaning up effects inside the custom hook.\n\n**Interview Follow-ups:**\n- How do custom hooks differ from regular functions?\n- Can custom hooks call other custom hooks? (Yes)\n- How do you test custom hooks? (Using `@testing-library\u002Freact-hooks`)\n\n**Best Practices:**\n- Keep custom hooks focused and single-purpose.\n- Return an object for clarity (named properties) or array for convenience.\n- Document dependencies and side effects.\n- Use TypeScript for better autocomplete.\n\n**Performance Considerations:**\n- Custom hooks can cause unnecessary re-renders if not optimized (e.g., returning new objects each render). Use `useCallback`\u002F`useMemo` inside hooks if needed.\n\n**Production Recommendations:**\n- Extract repetitive logic into custom hooks.\n- Use libraries like `react-query` for data fetching (which is itself a custom hook).\n- Write unit tests for custom hooks.\n\n**Node.js \u002F SSR Behavior:**\nCustom hooks that use browser-only APIs (like `localStorage`) need to check for `typeof window !== 'undefined'` or use `useEffect` to run only on client.\n\n**Latest React Patterns:**\n- Hooks can also be used in React Server Components but with restrictions (no state or effects).\n- React 19 may introduce `use` hook for promises, affecting custom hook patterns.\n\n**TypeScript Example:**\n```tsx\ninterface FetchState\u003CT> {\n  data: T | null;\n  loading: boolean;\n  error: Error | null;\n}\n\nfunction useFetch\u003CT>(url: string): FetchState\u003CT> {\n  const [data, setData] = useState\u003CT | null>(null);\n  \u002F\u002F ... rest\n  return { data, loading, error };\n}\n```\n\n**Interview Tip:**\nExplain that custom hooks let you share stateful logic without changing your component hierarchy. They are the replacement for render props and higher-order components.\n\n**Common Follow-up:**\n\"How do you share logic between two different hooks?\" (Call one hook inside another)\n\n**Real-world Example:**\nA dashboard app has multiple components fetching data from different endpoints. A `useApi` hook standardizes loading, error, and retry logic across all of them.\n\n**Advanced Notes:**\nCustom hooks can be composed: `useUserData` can call `useFetch` internally. React relies on the order of hook calls, so custom hooks must always call hooks unconditionally. Custom hooks can accept parameters and return values that are also hooks (like `useState` setter).",[231,232,233],"custom-hooks","reusability","abstraction",{"id":235,"category":41,"question":236,"answer":237,"level":213,"tags":238},29,"What is the Context API? How does it work and when should you use it over prop drilling?","**Concept Explanation:**\nContext API provides a way to pass data through the component tree without passing props down manually at every level. It creates a context object with a Provider component that supplies the value and a Consumer or `useContext` hook to consume it. It solves prop drilling but is not a full state management solution (performance concerns for high-frequency updates).\n\n**Syntax Explanation:**\n```jsx\nimport { createContext, useContext, useState } from 'react';\n\n\u002F\u002F Create context\nconst ThemeContext = createContext(null);\n\n\u002F\u002F Provider component\nfunction ThemeProvider({ children }) {\n  const [theme, setTheme] = useState('light');\n  return (\n    \u003CThemeContext.Provider value={{ theme, setTheme }}>\n      {children}\n    \u003C\u002FThemeContext.Provider>\n  );\n}\n\n\u002F\u002F Consumer component\nfunction ThemedButton() {\n  const { theme, setTheme } = useContext(ThemeContext);\n  return \u003Cbutton onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>\n    Current theme: {theme}\n  \u003C\u002Fbutton>;\n}\n```\n\n**Code Example:**\n```jsx\n\u002F\u002F User authentication context\nconst AuthContext = createContext(null);\n\nexport function AuthProvider({ children }) {\n  const [user, setUser] = useState(null);\n  const [loading, setLoading] = useState(true);\n\n  const login = async (email, password) => {\n    const userData = await api.login(email, password);\n    setUser(userData);\n  };\n\n  const logout = () => setUser(null);\n\n  return (\n    \u003CAuthContext.Provider value={{ user, loading, login, logout }}>\n      {children}\n    \u003C\u002FAuthContext.Provider>\n  );\n}\n\nexport function useAuth() {\n  const context = useContext(AuthContext);\n  if (!context) throw new Error('useAuth must be used within AuthProvider');\n  return context;\n}\n\n\u002F\u002F Usage in any component\nfunction ProfileButton() {\n  const { user, logout } = useAuth();\n  return user ? \u003Cbutton onClick={logout}>Logout {user.name}\u003C\u002Fbutton> : \u003CLoginButton \u002F>;\n}\n\n\u002F\u002F Context with reducer (for more complex state)\nconst TasksContext = createContext(null);\nconst TasksDispatchContext = createContext(null);\n\nfunction tasksReducer(tasks, action) {\n  switch (action.type) {\n    case 'add': return [...tasks, action.task];\n    case 'delete': return tasks.filter(t => t.id !== action.id);\n    default: return tasks;\n  }\n}\n\nfunction TasksProvider({ children }) {\n  const [tasks, dispatch] = useReducer(tasksReducer, []);\n  return (\n    \u003CTasksContext.Provider value={tasks}>\n      \u003CTasksDispatchContext.Provider value={dispatch}>\n        {children}\n      \u003C\u002FTasksDispatchContext.Provider>\n    \u003C\u002FTasksContext.Provider>\n  );\n}\n```\n\n**Execution Flow:**\n1. React creates a context object.\n2. Provider component holds a value.\n3. When the value changes, React re-renders all consumers that depend on it (using reference equality).\n4. `useContext` subscribes the component to the nearest Provider above.\n\n**Reactivity Explanation:**\nContext re-renders all consumers regardless of which part of the value they use. This can cause performance issues if the value is an object that changes frequently.\n\n**Practical Usage:**\n- Theme (dark\u002Flight mode).\n- User authentication state.\n- Language \u002F localization settings.\n- Feature flags.\n\n**Common Mistakes:**\n- Using context for high-frequency updates (e.g., every keystroke).\n- Providing a new object\u002Ffunction on every render (causes all consumers to re-render).\n- Not memoizing the context value.\n- Creating context with a default value that is useless (e.g., `null`) without proper error handling.\n\n**Interview Follow-ups:**\n- What is the difference between Context API and Redux?\n- How can you optimize Context to avoid unnecessary re-renders?\n- Can you have multiple contexts? (Yes)\n\n**Best Practices:**\n- Split contexts by domain (Auth, Theme, Settings) to reduce re-renders.\n- Memoize context value with `useMemo`.\n- Create custom hooks for consuming context to encapsulate logic and error handling.\n- Use context for low-frequency, global data.\n\n**Performance Considerations:**\n- Context re-renders all consumers when value changes, even if they only use a part of the value.\n- Solution: split contexts, or use libraries like `use-context-selector`.\n- For high-frequency updates, use state management like Zustand, Jotai, or Redux.\n\n**Production Recommendations:**\n- Use Context for dependency injection (e.g., service instances).\n- For app state that changes often (form inputs, real-time data), prefer local state or dedicated stores.\n- Profile re-renders with React DevTools.\n\n**Node.js \u002F SSR Behavior:**\nContext works on server; values are serialized as part of the component tree.\n\n**Latest React Patterns:**\n- React 18's `useSyncExternalStore` can bridge context with external stores.\n- Context can be used in Server Components but only static values (no state).\n\n**TypeScript Example:**\n```tsx\ninterface AuthContextType {\n  user: User | null;\n  login: (email: string, password: string) => Promise\u003Cvoid>;\n  logout: () => void;\n}\n\nconst AuthContext = createContext\u003CAuthContextType | null>(null);\n```\n\n**Interview Tip:**\nExplain that Context API is great for \"global\" but static or low-frequency data. For complex state with many updates, combine with `useReducer` or consider external libraries.\n\n**Common Follow-up:**\n\"How do you avoid re-rendering all consumers when the context value changes?\" (Split context into multiple smaller contexts, or memoize the value and use selectors)\n\n**Real-world Example:**\nAn e-commerce site uses context for user authentication, cart count (low frequency), and theme. The cart items (high frequency) are managed by Zustand.\n\n**Advanced Notes:**\nReact's `createContext` also has a `displayName` for DevTools. The Provider value is compared with `Object.is`. If you pass an object literal, it will be new on every render, causing re-renders even if data hasn't changed. Always memoize the value object.",[239,240,241],"context","prop-drilling","state-management",{"id":243,"category":41,"question":244,"answer":245,"level":213,"tags":246},30,"What is useReducer and when would you use it instead of useState? Provide an example.","**Concept Explanation:**\n`useReducer` is a hook for managing complex state logic that involves multiple sub-values or when the next state depends on the previous state in non-trivial ways. It follows the reducer pattern (state, action) => newState, similar to Redux. It's ideal for state with multiple transitions or when state updates are interdependent.\n\n**Syntax Explanation:**\n```jsx\nconst [state, dispatch] = useReducer(reducer, initialState, init);\n\nfunction reducer(state, action) {\n  switch (action.type) {\n    case 'increment': return { count: state.count + 1 };\n    case 'decrement': return { count: state.count - 1 };\n    default: return state;\n  }\n}\n\n\u002F\u002F Usage\nconst [state, dispatch] = useReducer(reducer, { count: 0 });\ndispatch({ type: 'increment' });\n```\n\n**Code Example:**\n```jsx\n\u002F\u002F Complex form state management\nconst initialState = {\n  name: '',\n  email: '',\n  age: '',\n  errors: {},\n  isDirty: false,\n};\n\nfunction formReducer(state, action) {\n  switch (action.type) {\n    case 'SET_FIELD':\n      return {\n        ...state,\n        [action.field]: action.value,\n        isDirty: true,\n        errors: { ...state.errors, [action.field]: null },\n      };\n    case 'SET_ERRORS':\n      return { ...state, errors: action.errors };\n    case 'RESET':\n      return { ...initialState };\n    case 'VALIDATE':\n      const newErrors = {};\n      if (!state.name) newErrors.name = 'Required';\n      if (!state.email.includes('@')) newErrors.email = 'Invalid email';\n      return { ...state, errors: newErrors };\n    default:\n      return state;\n  }\n}\n\nfunction SignupForm() {\n  const [state, dispatch] = useReducer(formReducer, initialState);\n\n  const handleChange = (e) => {\n    dispatch({ type: 'SET_FIELD', field: e.target.name, value: e.target.value });\n  };\n\n  const handleSubmit = () => {\n    dispatch({ type: 'VALIDATE' });\n    if (Object.values(state.errors).every(e => !e)) {\n      submit(state);\n    }\n  };\n\n  return (\n    \u003Cform>\n      \u003Cinput name=\"name\" value={state.name} onChange={handleChange} \u002F>\n      {state.errors.name && \u003Cspan>{state.errors.name}\u003C\u002Fspan>}\n      \u003Cinput name=\"email\" value={state.email} onChange={handleChange} \u002F>\n      {state.errors.email && \u003Cspan>{state.errors.email}\u003C\u002Fspan>}\n      \u003Cbutton onClick={handleSubmit}>Submit\u003C\u002Fbutton>\n    \u003C\u002Fform>\n  );\n}\n\n\u002F\u002F Shopping cart example\nconst cartReducer = (state, action) => {\n  switch (action.type) {\n    case 'add':\n      const existing = state.items.find(item => item.id === action.item.id);\n      if (existing) {\n        return {\n          ...state,\n          items: state.items.map(item =>\n            item.id === action.item.id ? { ...item, quantity: item.quantity + 1 } : item\n          ),\n          total: state.total + action.item.price,\n        };\n      }\n      return {\n        ...state,\n        items: [...state.items, { ...action.item, quantity: 1 }],\n        total: state.total + action.item.price,\n      };\n    case 'remove':\n      const itemToRemove = state.items.find(item => item.id === action.id);\n      return {\n        ...state,\n        items: state.items.filter(item => item.id !== action.id),\n        total: state.total - (itemToRemove.price * itemToRemove.quantity),\n      };\n    case 'clear':\n      return { items: [], total: 0 };\n    default:\n      return state;\n  }\n};\n```\n\n**Execution Flow:**\n1. Call `dispatch` with an action object.\n2. React runs the reducer function with current state and action.\n3. Reducer returns new state.\n4. React schedules a re-render with the new state.\n\n**Reactivity Explanation:**\n`useReducer` provides predictable state transitions. The dispatch function is stable (never changes), so it can be passed down without causing child re-renders.\n\n**Practical Usage:**\n- Complex forms with interdependent fields.\n- Shopping cart with add\u002Fremove\u002Fupdate quantity.\n- State machines (multi-step wizards).\n- Any state where next value depends on previous in many ways.\n\n**Common Mistakes:**\n- Using `useReducer` when `useState` with multiple setters would be simpler.\n- Mutating state in reducer (must return new object).\n- Forgetting to handle the default action (return state).\n- Not using action types as constants.\n\n**Interview Follow-ups:**\n- What is the difference between `useReducer` and Redux?\n- How do you combine multiple reducers?\n- Can `useReducer` replace `useState`? (Yes, but overkill)\n\n**Best Practices:**\n- Define action types as constants or enums.\n- Keep reducer pure (no side effects).\n- Use `useReducer` with Context API for global state.\n- Use `immer` or similar for complex nested updates.\n\n**Performance Considerations:**\n- `useReducer` can reduce re-renders compared to multiple `useState` calls because you dispatch one action to update multiple related fields.\n- The dispatch function is stable, good for passing to memoized children.\n\n**Production Recommendations:**\n- Use `useReducer` for complex component state.\n- For global state, consider Zustand or Redux Toolkit.\n- Always initialize with lazy initialization for performance if initialState is expensive.\n\n**Node.js \u002F SSR Behavior:**\nWorks similarly on server; state is initialized during SSR.\n\n**Latest React Patterns:**\n- Combine `useReducer` with Context for a lightweight Redux alternative.\n- Use `useTransition` with reducer actions to mark as non-urgent.\n\n**TypeScript Example:**\n```tsx\ntype Action =\n  | { type: 'increment'; payload: number }\n  | { type: 'decrement' }\n  | { type: 'reset' };\n\nconst reducer = (state: number, action: Action): number => {\n  switch (action.type) {\n    case 'increment': return state + action.payload;\n    case 'decrement': return state - 1;\n    case 'reset': return 0;\n    default: return state;\n  }\n};\n```\n\n**Interview Tip:**\nExplain that `useReducer` helps when state logic is complex, involves multiple sub-values, or when updates rely on previous state in non-trivial ways.\n\n**Common Follow-up:**\n\"How do you handle side effects after a reducer action?\" (use `useEffect` with state as dependency, or use middleware pattern)\n\n**Real-world Example:**\nA todo app with actions: add, toggle, delete, edit, clear completed – `useReducer` makes the transitions explicit and testable.\n\n**Advanced Notes:**\n`useReducer` supports lazy initialization via third argument `init`. The initial function can compute initial state from props. React also provides `useReducer` with `React.memo` for performance. For very large state trees, consider using `useReducer` with `immer` for immutable updates.",[247,45,248],"useReducer","complex-state",{"id":250,"category":58,"question":251,"answer":252,"level":213,"tags":253},31,"Explain React's reconciliation and diffing algorithm. How does it decide which components to update?","**Concept Explanation:**\nReconciliation is the process by which React updates the DOM by comparing the current virtual DOM tree with the new one. The diffing algorithm makes two key assumptions: 1) Elements of different types produce different trees; 2) Stable keys among siblings indicate which elements can be reused. React then generates a minimal set of mutations to apply to the real DOM.\n\n**Syntax Explanation:**\n(No direct code – internal algorithm)\n\n**How It Works:**\n1. **Different element types:** If the root element type changes (e.g., `div` → `span`), React tears down the old tree and builds a new one from scratch.\n2. **Same element type:** React compares attributes\u002Fprops and updates only changed ones, then recursively reconciles children.\n3. **Lists\u002Fkeys:** React uses keys to match children in the old and new trees. Without keys, it uses index-based comparison (less efficient).\n\n**Code Example (Illustrative):**\n```jsx\n\u002F\u002F Before\n\u003Cdiv>\n  \u003Cp key=\"1\">First\u003C\u002Fp>\n  \u003Cp key=\"2\">Second\u003C\u002Fp>\n\u003C\u002Fdiv>\n\n\u002F\u002F After\n\u003Cdiv>\n  \u003Cp key=\"3\">Third\u003C\u002Fp>\n  \u003Cp key=\"1\">First\u003C\u002Fp>\n  \u003Cp key=\"2\">Second\u003C\u002Fp>\n\u003C\u002Fdiv>\n\n\u002F\u002F With keys, React recognizes that first \u003Cp> is new, the rest are moved.\n\u002F\u002F Without keys, React would destroy the first two and rebuild them.\n```\n\n**Execution Flow:**\n1. Render phase: React builds the new virtual DOM tree by calling component functions (or `render` methods).\n2. Diffing: React walks the tree, comparing new and old nodes.\n3. Commit phase: React applies the changes (DOM updates).\n\n**Reactivity Explanation:**\nReconciliation is triggered by state\u002Fprops changes. The algorithm determines which parts of the DOM need updates.\n\n**Practical Usage:**\n- Use `key` props to help React identify items in lists.\n- Keep component tree structure stable to avoid unnecessary tree teardowns.\n\n**Common Mistakes:**\n- Using index as key when list order can change (causes state bugs and performance issues).\n- Changing root component type unnecessarily (e.g., wrapping a component conditionally with a different element).\n\n**Interview Follow-ups:**\n- Why does React need keys?\n- What happens when you use `Math.random()` as key?\n- How does reconciliation handle nested components?\n\n**Best Practices:**\n- Always provide stable, unique keys for list items.\n- Avoid random keys or array indices unless list is static.\n- Keep component structure consistent across renders.\n\n**Performance Considerations:**\n- Reconciliation is O(n) in the number of elements (due to heuristics).\n- Frequent teardowns (changing root types) are expensive.\n- Keys reduce unnecessary mutations.\n\n**Production Recommendations:**\n- Use React DevTools profiler to identify reconciliation overhead.\n- Avoid unnecessary state updates that cause large tree diffs.\n- Use `React.memo` to skip diffing subtrees.\n\n**Node.js \u002F SSR Behavior:**\nReconciliation doesn't happen on server (no DOM). Only the first virtual DOM is serialized to HTML.\n\n**Latest React Patterns:**\n- React Fiber (16+) allows reconciliation to be interruptible and prioritized.\n- Concurrent features (useTransition) can pause reconciliation.\n\n**TypeScript Example:**\n(Not applicable)\n\n**Interview Tip:**\nExplain that the virtual DOM diff is fast due to assumptions; keys are crucial for lists. Emphasize that React avoids O(n³) by using heuristics.\n\n**Common Follow-up:**\n\"How does React compare component types?\" (Uses reference equality; a new function reference means new component type)\n\n**Real-world Example:**\nA list of 1000 items reorderable by dragging. Without stable keys, moving an item would cause React to destroy and recreate 1000 DOM nodes. With stable IDs, React just moves the DOM node.\n\n**Advanced Notes:**\nReact also has a \"fiber\" architecture that allows reconciliation work to be split into chunks, yielding to the browser for high-priority updates. The `shouldComponentUpdate` or `React.memo` can skip reconciliation of entire subtrees.",[136,254,13,70],"diffing",{"id":256,"category":175,"question":257,"answer":258,"level":213,"tags":259},32,"What are code splitting and lazy loading? How do you implement them with React.lazy and Suspense?","**Concept Explanation:**\nCode splitting is a technique to split your JavaScript bundle into smaller chunks loaded on demand. Lazy loading delays loading of components until they are needed (e.g., when navigating to a route). React provides `React.lazy` for dynamic imports and `Suspense` as a fallback UI while the component loads.\n\n**Syntax Explanation:**\n```jsx\nimport { lazy, Suspense } from 'react';\n\n\u002F\u002F Lazy load component\nconst MyComponent = lazy(() => import('.\u002FMyComponent'));\n\n\u002F\u002F Use with Suspense\n\u003CSuspense fallback={\u003Cdiv>Loading...\u003C\u002Fdiv>}>\n  \u003CMyComponent \u002F>\n\u003C\u002FSuspense>\n```\n\n**Code Example:**\n```jsx\nimport { BrowserRouter, Routes, Route } from 'react-router-dom';\nimport { lazy, Suspense, useState } from 'react';\n\n\u002F\u002F Route-based code splitting\nconst Home = lazy(() => import('.\u002Fpages\u002FHome'));\nconst About = lazy(() => import('.\u002Fpages\u002FAbout'));\nconst Dashboard = lazy(() => import('.\u002Fpages\u002FDashboard'));\nconst HeavyChart = lazy(() => import('.\u002Fcomponents\u002FHeavyChart'));\n\nfunction App() {\n  const [showChart, setShowChart] = useState(false);\n\n  return (\n    \u003CBrowserRouter>\n      \u003CSuspense fallback={\u003Cdiv className=\"loading-spinner\">Loading...\u003C\u002Fdiv>}>\n        \u003CRoutes>\n          \u003CRoute path=\"\u002F\" element={\u003CHome \u002F>} \u002F>\n          \u003CRoute path=\"\u002Fabout\" element={\u003CAbout \u002F>} \u002F>\n          \u003CRoute path=\"\u002Fdashboard\" element={\u003CDashboard \u002F>} \u002F>\n        \u003C\u002FRoutes>\n      \u003C\u002FSuspense>\n\n      \u003Cbutton onClick={() => setShowChart(true)}>Show Chart\u003C\u002Fbutton>\n      {showChart && (\n        \u003CSuspense fallback={\u003Cdiv>Loading chart...\u003C\u002Fdiv>}>\n          \u003CHeavyChart \u002F>\n        \u003C\u002FSuspense>\n      )}\n    \u003C\u002FBrowserRouter>\n  );\n}\n\n\u002F\u002F Named exports with lazy\nconst Modal = lazy(() => import('.\u002FModal').then(module => ({ default: module.Modal })));\n\n\u002F\u002F Custom loading component\nfunction LazyWrapper({ children }) {\n  return (\n    \u003CSuspense fallback={\u003CSkeleton \u002F>}>\n      {children}\n    \u003C\u002FSuspense>\n  );\n}\n```\n\n**Execution Flow:**\n1. `React.lazy` returns a component that triggers dynamic `import()` when rendered.\n2. During render, React catches the promise and suspends rendering.\n3. The nearest `\u003CSuspense>` boundary shows the `fallback` content.\n4. Once the promise resolves, React renders the loaded component.\n\n**Reactivity Explanation:**\nThe loaded component becomes part of the component tree after resolution. No further effects needed.\n\n**Practical Usage:**\n- Route-based splitting for SPAs.\n- Lazy loading heavy components (charts, editors, modals).\n- Reducing initial bundle size.\n\n**Common Mistakes:**\n- Not wrapping lazy components with Suspense (causes error).\n- Lazy loading small components (adds overhead).\n- Using lazy for components that appear immediately above the fold.\n- Not providing a meaningful fallback (e.g., empty div).\n\n**Interview Follow-ups:**\n- How does `React.lazy` differ from dynamic imports?\n- Can you use lazy with server-side rendering?\n- What is the difference between `Suspense` for data fetching and lazy loading?\n\n**Best Practices:**\n- Lazy load routes in large applications.\n- Use Suspense with a loading skeleton for better UX.\n- Group related lazy components under a single Suspense.\n- Preload lazy components on hover for perceived performance.\n\n**Performance Considerations:**\n- Reduces initial JavaScript bundle size.\n- Adds minimal overhead for the import promise.\n- Too many tiny chunks can increase HTTP requests (mitigate with bundler config).\n\n**Production Recommendations:**\n- Use Webpack or Vite's code splitting features alongside `React.lazy`.\n- Set up preloading: `const prefetch = () => import('.\u002FHeavy');` on hover.\n- Use `webpackChunkName` magic comment for named chunks.\n\n**Node.js \u002F SSR Behavior:**\n`React.lazy` does not work with traditional SSR because it requires Suspense on the client. Use frameworks like Next.js for SSR with dynamic imports.\n\n**Latest React Patterns:**\n- React 18 Suspense can also handle data fetching (with libraries like Relay, Next.js).\n- `use` hook (React 19) for promise consumption without Suspense.\n\n**TypeScript Example:**\n```tsx\nconst LazyComponent = lazy(() => import('.\u002FComponent') as Promise\u003C{ default: React.ComponentType\u003CProps> }>);\n```\n\n**Interview Tip:**\nExplain that code splitting reduces initial load time at the cost of showing a loading indicator. It's essential for large SPAs.\n\n**Common Follow-up:**\n\"How do you test lazy-loaded components?\" (Use `waitFor` and act patterns in React Testing Library; simulate module loading)\n\n**Real-world Example:**\nAn analytics dashboard loads the main UI immediately, but the heavy charts library is lazy-loaded only when the user navigates to the analytics tab.\n\n**Advanced Notes:**\nYou can combine lazy loading with error boundaries to handle loading failures. Also, you can use `SuspenseList` (experimental) to coordinate loading order of multiple lazy components.",[260,261,262,263],"code-splitting","lazy-loading","suspense","react-lazy",{"id":265,"category":266,"question":267,"answer":268,"level":213,"tags":269},33,"Error Handling","What are error boundaries in React? How do you implement them and what are their limitations?","**Concept Explanation:**\nError boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of crashing the whole app. They only catch errors during rendering, lifecycle methods, and constructors. They do not catch errors in event handlers, async code, or server-side rendering.\n\n**Syntax Explanation:**\n```jsx\nclass ErrorBoundary extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = { hasError: false };\n  }\n\n  static getDerivedStateFromError(error) {\n    return { hasError: true };\n  }\n\n  componentDidCatch(error, errorInfo) {\n    console.error('Error caught:', error, errorInfo);\n  }\n\n  render() {\n    if (this.state.hasError) {\n      return \u003Ch1>Something went wrong.\u003C\u002Fh1>;\n    }\n    return this.props.children;\n  }\n}\n```\n\n**Code Example:**\n```jsx\nimport React from 'react';\nimport { logErrorToService } from '.\u002Flogging';\n\n\u002F\u002F Generic error boundary\nclass ErrorBoundary extends React.Component {\n  state = { hasError: false, error: null };\n\n  static getDerivedStateFromError(error) {\n    return { hasError: true, error };\n  }\n\n  componentDidCatch(error, errorInfo) {\n    \u002F\u002F Log error to monitoring service\n    logErrorToService(error, errorInfo);\n  }\n\n  resetError = () => {\n    this.setState({ hasError: false, error: null });\n  };\n\n  render() {\n    if (this.state.hasError) {\n      return (\n        \u003Cdiv className=\"error-fallback\">\n          \u003Ch2>Oops, something went wrong\u003C\u002Fh2>\n          \u003Cdetails>{this.state.error?.toString()}\u003C\u002Fdetails>\n          \u003Cbutton onClick={this.resetError}>Try again\u003C\u002Fbutton>\n        \u003C\u002Fdiv>\n      );\n    }\n    return this.props.children;\n  }\n}\n\n\u002F\u002F Usage\nfunction App() {\n  return (\n    \u003CErrorBoundary>\n      \u003CProfile \u002F>\n    \u003C\u002FErrorBoundary>\n  );\n}\n\n\u002F\u002F Multiple boundaries\nfunction Dashboard() {\n  return (\n    \u003Cdiv>\n      \u003CErrorBoundary fallback={\u003Cdiv>Widget A crashed\u003C\u002Fdiv>}>\n        \u003CWidgetA \u002F>\n      \u003C\u002FErrorBoundary>\n      \u003CErrorBoundary fallback={\u003Cdiv>Widget B crashed\u003C\u002Fdiv>}>\n        \u003CWidgetB \u002F>\n      \u003C\u002FErrorBoundary>\n    \u003C\u002Fdiv>\n  );\n}\n\n\u002F\u002F With reset using key\nfunction UserProfile({ userId }) {\n  const [key, setKey] = useState(0);\n  return (\n    \u003CErrorBoundary key={key}>\n      \u003CProfileContent userId={userId} onError={() => setKey(prev => prev + 1)} \u002F>\n    \u003C\u002FErrorBoundary>\n  );\n}\n```\n\n**Execution Flow:**\n1. An error occurs in a child component.\n2. React propagates the error up to the nearest error boundary.\n3. `static getDerivedStateFromError` is called to update state.\n4. `componentDidCatch` is called for side effects (logging).\n5. The error boundary renders fallback UI.\n\n**Reactivity Explanation:**\nError boundaries are class components only (as of React 18). After state update, they re-render to show fallback.\n\n**Practical Usage:**\n- Wrapping entire app to prevent crashes.\n- Isolating widgets\u002Fcomponents that may fail independently.\n- Providing user-friendly error messages.\n\n**Common Mistakes:**\n- Expecting error boundaries to catch async errors (event handlers, setTimeout).\n- Using functional components as error boundaries (not possible).\n- Not resetting the boundary after error (user cannot recover).\n\n**Interview Follow-ups:**\n- Why can't error boundaries be functional components?\n- How do you handle errors in event handlers?\n- What is the difference between `getDerivedStateFromError` and `componentDidCatch`?\n\n**Best Practices:**\n- Place error boundaries at strategic levels (app root, feature boundaries, widget level).\n- Provide a way for users to reset the broken UI.\n- Log errors to monitoring services.\n- Use `react-error-boundary` library for simpler syntax.\n\n**Performance Considerations:**\n- Error boundaries add a layer of component tree but negligible overhead.\n- Only catch errors that occur during render, not in user interactions.\n\n**Production Recommendations:**\n- Use `react-error-boundary` for a pre-built, flexible solution.\n- Combine with `Sentry` or `LogRocket` for error tracking.\n- Provide fallback UI that includes an error ID for support.\n\n**Node.js \u002F SSR Behavior:**\n`componentDidCatch` does not run on server (only client). Errors during SSR crash the server process unless handled.\n\n**Latest React Patterns:**\n- React 18 still requires class components for error boundaries.\n- Future React versions may introduce `useErrorBoundary` hook.\n\n**TypeScript Example:**\n```tsx\ninterface ErrorBoundaryProps {\n  children: React.ReactNode;\n  fallback?: React.ReactNode;\n}\n\ninterface ErrorBoundaryState {\n  hasError: boolean;\n  error: Error | null;\n}\n\nclass ErrorBoundary extends React.Component\u003CErrorBoundaryProps, ErrorBoundaryState> {\n  \u002F\u002F ...\n}\n```\n\n**Interview Tip:**\nExplain that error boundaries are the only case where you still need class components. They prevent the whole app from unmounting due to rendering errors.\n\n**Common Follow-up:**\n\"How do you handle errors in event handlers?\" (Use try\u002Fcatch and update state manually)\n\n**Real-world Example:**\nA dashboard with multiple data widgets. If one widget fails to render due to malformed data, an error boundary shows a fallback component while other widgets continue working.\n\n**Advanced Notes:**\nError boundaries can be nested; an error will propagate to the nearest parent boundary. You can recover by changing the `key` prop of the boundary to force remount. The `react-error-boundary` library provides a `useErrorHandler` hook for catching async errors.",[270,189,271],"error-boundaries","class-components",{"id":273,"category":274,"question":275,"answer":276,"level":213,"tags":277},34,"DOM Interaction","What are forwardRefs and useImperativeHandle? How do you expose DOM refs or component methods to parent components?","**Concept Explanation:**\n`forwardRef` allows a component to forward a ref to one of its children (typically a DOM element). `useImperativeHandle` customizes the ref value exposed to parent components, enabling you to expose specific methods (e.g., `focus`, `reset`) instead of the whole DOM node. This pattern is useful for controlling child components imperatively.\n\n**Syntax Explanation:**\n```jsx\n\u002F\u002F Forward ref to a DOM element\nconst FancyInput = React.forwardRef((props, ref) => (\n  \u003Cinput ref={ref} className=\"fancy\" {...props} \u002F>\n));\n\n\u002F\u002F Parent usage\nfunction Parent() {\n  const inputRef = useRef();\n  useEffect(() => inputRef.current.focus(), []);\n  return \u003CFancyInput ref={inputRef} \u002F>;\n}\n```\n\n**Code Example:**\n```jsx\nimport { forwardRef, useImperativeHandle, useRef, useState } from 'react';\n\n\u002F\u002F Exposing methods to parent\nconst CustomInput = forwardRef((props, ref) => {\n  const inputRef = useRef(null);\n  const [value, setValue] = useState('');\n\n  \u002F\u002F Expose only specific methods\n  useImperativeHandle(ref, () => ({\n    focus: () => inputRef.current.focus(),\n    clear: () => setValue(''),\n    getValue: () => value,\n  }));\n\n  return (\n    \u003Cinput\n      ref={inputRef}\n      value={value}\n      onChange={(e) => setValue(e.target.value)}\n      {...props}\n    \u002F>\n  );\n});\n\n\u002F\u002F Parent component using imperative methods\nfunction Form() {\n  const nameInputRef = useRef(null);\n  const emailInputRef = useRef(null);\n\n  const handleSubmit = () => {\n    const name = nameInputRef.current?.getValue();\n    const email = emailInputRef.current?.getValue();\n    console.log({ name, email });\n  };\n\n  const resetForm = () => {\n    nameInputRef.current?.clear();\n    emailInputRef.current?.clear();\n    nameInputRef.current?.focus();\n  };\n\n  return (\n    \u003Cdiv>\n      \u003CCustomInput ref={nameInputRef} placeholder=\"Name\" \u002F>\n      \u003CCustomInput ref={emailInputRef} placeholder=\"Email\" \u002F>\n      \u003Cbutton onClick={handleSubmit}>Submit\u003C\u002Fbutton>\n      \u003Cbutton onClick={resetForm}>Reset\u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  );\n}\n\n\u002F\u002F Forwarding ref with multiple DOM elements\nconst FocusableDiv = forwardRef(({ children }, ref) => {\n  const divRef = useRef(null);\n\n  useImperativeHandle(ref, () => ({\n    focus: () => divRef.current.focus(),\n    scrollIntoView: () => divRef.current.scrollIntoView(),\n  }));\n\n  return \u003Cdiv ref={divRef} tabIndex={-1}>{children}\u003C\u002Fdiv>;\n});\n```\n\n**Execution Flow:**\n1. Parent creates a ref with `useRef` and passes it to a child component via the `ref` prop.\n2. Child uses `forwardRef` to receive the ref as second parameter.\n3. Child either attaches the ref directly to a DOM element or uses `useImperativeHandle` to customize the ref value.\n4. Parent can then call methods or access properties via `ref.current`.\n\n**Reactivity Explanation:**\nRefs are mutable objects that persist across renders but do not trigger re-renders when changed.\n\n**Practical Usage:**\n- Creating reusable form components that expose validation methods.\n- Managing focus programmatically.\n- Integrating with third-party libraries that require DOM access.\n- Building component libraries with controlled refs.\n\n**Common Mistakes:**\n- Forgetting to wrap component with `forwardRef` when using `ref` prop.\n- Overusing imperative handles when declarative state is sufficient.\n- Not memoizing the object passed to `useImperativeHandle` (causes unnecessary updates).\n\n**Interview Follow-ups:**\n- When would you use `forwardRef` instead of passing a ref as a regular prop?\n- What is the difference between `ref` prop and `forwardRef`?\n- Can you use `forwardRef` with functional components only?\n\n**Best Practices:**\n- Use `forwardRef` for components that expose a DOM element.\n- Use `useImperativeHandle` sparingly; prefer declarative APIs.\n- Name custom methods clearly (`focus`, `reset`, `validate`).\n- Combine with `React.memo` to avoid unnecessary re-renders.\n\n**Performance Considerations:**\n- `forwardRef` adds negligible overhead.\n- `useImperativeHandle` object should be memoized with `useCallback`\u002F`useMemo` to avoid stale references.\n\n**Production Recommendations:**\n- In component libraries, always forward refs to underlying DOM elements for accessibility.\n- Document exposed imperative methods.\n- Use TypeScript to define ref type interfaces.\n\n**Node.js \u002F SSR Behavior:**\nRefs are only populated on the client after hydration. On server, ref.current is null.\n\n**Latest React Patterns:**\n- React 19 may simplify ref forwarding for component libraries.\n- `useRef` with `forwardRef` is standard pattern.\n\n**TypeScript Example:**\n```tsx\nexport interface CustomInputRef {\n  focus: () => void;\n  clear: () => void;\n  getValue: () => string;\n}\n\nconst CustomInput = forwardRef\u003CCustomInputRef, InputProps>((props, ref) => {\n  useImperativeHandle(ref, () => ({\n    focus: () => inputRef.current?.focus(),\n    clear: () => setValue(''),\n    getValue: () => value,\n  }));\n  \u002F\u002F ...\n});\n\n\u002F\u002F Usage\nconst ref = useRef\u003CCustomInputRef>(null);\n```\n\n**Interview Tip:**\nExplain that `forwardRef` is necessary because `ref` is not a normal prop; it's reserved. `useImperativeHandle` gives control over what is exposed, improving encapsulation.\n\n**Common Follow-up:**\n\"How do you forward multiple refs?\" (Use a single ref that contains multiple fields or use an object ref)\n\n**Real-world Example:**\nA custom date picker component that exposes methods `openCalendar`, `closeCalendar`, `getDate`. Parent can call these without knowing the internal implementation.\n\n**Advanced Notes:**\nYou can also forward refs to class components. `forwardRef` can be combined with `React.memo`. The `useImperativeHandle` dependency array should include all values used in the exposed object to avoid stale closures.",[278,279,156,157],"forwardRef","useImperativeHandle",{"id":281,"category":58,"question":282,"answer":283,"level":213,"tags":284},35,"What are portals in React? How do they work and when would you use them?","**Concept Explanation:**\nPortals provide a way to render children into a DOM node that exists outside the parent component's DOM hierarchy. This is useful for modals, tooltips, dropdowns, and popovers that need to break out of overflow or stacking context issues. Event bubbling works normally through portals.\n\n**Syntax Explanation:**\n```jsx\nimport { createPortal } from 'react-dom';\n\nfunction Modal({ children, isOpen }) {\n  if (!isOpen) return null;\n  \u002F\u002F Render into a different DOM node (e.g., body)\n  return createPortal(\n    \u003Cdiv className=\"modal-overlay\">\n      \u003Cdiv className=\"modal-content\">{children}\u003C\u002Fdiv>\n    \u003C\u002Fdiv>,\n    document.getElementById('portal-root') \u002F\u002F target DOM node\n  );\n}\n```\n\n**Code Example:**\n```jsx\n\u002F\u002F index.html\n\u003Cdiv id=\"root\">\u003C\u002Fdiv>\n\u003Cdiv id=\"modal-root\">\u003C\u002Fdiv>\n\n\u002F\u002F Modal component with portal\nfunction Modal({ children, isOpen, onClose }) {\n  if (!isOpen) return null;\n\n  return createPortal(\n    \u003Cdiv className=\"modal-backdrop\" onClick={onClose}>\n      \u003Cdiv className=\"modal\" onClick={(e) => e.stopPropagation()}>\n        \u003Cbutton className=\"close-btn\" onClick={onClose}>×\u003C\u002Fbutton>\n        {children}\n      \u003C\u002Fdiv>\n    \u003C\u002Fdiv>,\n    document.getElementById('modal-root')\n  );\n}\n\n\u002F\u002F Tooltip using portal\nfunction Tooltip({ children, text, isVisible }) {\n  const [position, setPosition] = useState({ top: 0, left: 0 });\n  const triggerRef = useRef();\n\n  useEffect(() => {\n    if (isVisible && triggerRef.current) {\n      const rect = triggerRef.current.getBoundingClientRect();\n      setPosition({ top: rect.bottom + 5, left: rect.left });\n    }\n  }, [isVisible]);\n\n  return (\n    \u003Cspan ref={triggerRef}>\n      {children}\n      {isVisible && createPortal(\n        \u003Cdiv className=\"tooltip\" style={{ position: 'absolute', top: position.top, left: position.left }}>\n          {text}\n        \u003C\u002Fdiv>,\n        document.body\n      )}\n    \u003C\u002Fspan>\n  );\n}\n\n\u002F\u002F Usage in app\nfunction App() {\n  const [isModalOpen, setIsModalOpen] = useState(false);\n  return (\n    \u003Cdiv style={{ overflow: 'hidden', position: 'relative' }}>\n      \u003Cbutton onClick={() => setIsModalOpen(true)}>Open Modal\u003C\u002Fbutton>\n      \u003CModal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)}>\n        \u003Ch2>Modal Content\u003C\u002Fh2>\n        \u003Cp>This is rendered outside the parent's stacking context.\u003C\u002Fp>\n      \u003C\u002FModal>\n    \u003C\u002Fdiv>\n  );\n}\n```\n\n**Execution Flow:**\n1. `createPortal` is called with children and a DOM container.\n2. React renders the children into the specified container instead of the parent component's DOM node.\n3. Despite different DOM location, the portal children stay in the React tree: events bubble through the React component hierarchy, not the DOM hierarchy.\n\n**Reactivity Explanation:**\nPortal updates are still driven by parent component state\u002Fprops. The portal content re-renders normally.\n\n**Practical Usage:**\n- Modals, dialogs, popups.\n- Tooltips, popovers.\n- Dropdown menus that need to avoid clipped overflow.\n- Loading indicators that overlay the whole page.\n\n**Common Mistakes:**\n- Not ensuring the portal container exists in the DOM (null target).\n- Forgetting to handle event propagation (e.g., clicks on modal backdrop closing modal).\n- Using portals for everything – unnecessary complexity.\n\n**Interview Follow-ups:**\n- How does event bubbling work with portals?\n- Can you use portals with SSR?\n- What is the difference between portal and `ReactDOM.render`?\n\n**Best Practices:**\n- Create a dedicated portal root element (e.g., `\u003Cdiv id=\"portal-root\">`) in HTML.\n- Use portals for components that need to break out of ancestor stacking contexts.\n- Manage focus appropriately (return focus to trigger when modal closes).\n\n**Performance Considerations:**\n- Portals have negligible overhead; the portal element is just a DOM container.\n- Large portal content will still be re-rendered as usual.\n\n**Production Recommendations:**\n- Use a reusable `\u003CPortal>` component that accepts a container prop.\n- For SSR, check `typeof window !== 'undefined'` before accessing `document`.\n- Combine with React Context for global modal management.\n\n**Node.js \u002F SSR Behavior:**\nPortals require DOM API; on server, you should not attempt to render portals. Use `useEffect` or conditionally render only on client.\n\n**Latest React Patterns:**\n- React 18 supports portals with concurrent rendering seamlessly.\n- Many UI libraries (Material-UI, Ant Design) use portals for modals.\n\n**TypeScript Example:**\n```tsx\ninterface PortalProps {\n  children: React.ReactNode;\n  container?: HTMLElement;\n}\n\nconst Portal: React.FC\u003CPortalProps> = ({ children, container = document.body }) => {\n  const [mounted, setMounted] = useState(false);\n  useEffect(() => setMounted(true), []);\n  if (!mounted) return null;\n  return createPortal(children, container);\n};\n```\n\n**Interview Tip:**\nExplain that portals let you break out of CSS constraints (overflow, z-index) while preserving React's event system. They are essential for UI components that overlay content.\n\n**Common Follow-up:**\n\"How do you handle focus management with portals?\" (Use `useEffect` to focus the portal content or return focus on close)\n\n**Real-world Example:**\nA rich text editor inside a scrollable container with a color picker dropdown. Without portals, the dropdown would be clipped by overflow: hidden. Portal renders the dropdown to body, solving the clipping issue.\n\n**Advanced Notes:**\nPortals are implemented in React using a separate DOM render path but same virtual DOM reconciliation. Events bubble through parent components because React stores a reference to the fiber tree. You can also render multiple portals to the same container.",[285,157,286,287],"portals","modals","tooltips",{"id":289,"category":109,"question":290,"answer":291,"level":213,"tags":292},36,"How do you implement debouncing and throttling in React? Give examples for search inputs and scroll events.","**Concept Explanation:**\nDebouncing delays function execution until after a pause (e.g., user stops typing). Throttling limits function execution to once per interval (e.g., scroll handler). In React, you need to use `useRef` or `useCallback` to preserve timer references across re-renders and avoid creating multiple timers.\n\n**Syntax Explanation:**\n```jsx\n\u002F\u002F Debounce with useCallback and useRef\nconst debouncedSearch = useCallback(\n  debounce((term) => fetchResults(term), 500),\n  []\n);\n\n\u002F\u002F Throttle with useRef\nconst throttledScroll = useRef(throttle(() => handleScroll(), 200)).current;\n```\n\n**Code Example:**\n```jsx\nimport { useCallback, useRef, useEffect, useState } from 'react';\n\n\u002F\u002F Custom debounce hook\nfunction useDebounce(value, delay) {\n  const [debouncedValue, setDebouncedValue] = useState(value);\n\n  useEffect(() => {\n    const timer = setTimeout(() => setDebouncedValue(value), delay);\n    return () => clearTimeout(timer);\n  }, [value, delay]);\n\n  return debouncedValue;\n}\n\n\u002F\u002F Custom throttle hook\nfunction useThrottle(value, limit) {\n  const [throttledValue, setThrottledValue] = useState(value);\n  const lastRun = useRef(Date.now());\n\n  useEffect(() => {\n    const now = Date.now();\n    if (now - lastRun.current >= limit) {\n      setThrottledValue(value);\n      lastRun.current = now;\n    } else {\n      const timer = setTimeout(() => {\n        setThrottledValue(value);\n        lastRun.current = Date.now();\n      }, limit - (now - lastRun.current));\n      return () => clearTimeout(timer);\n    }\n  }, [value, limit]);\n\n  return throttledValue;\n}\n\n\u002F\u002F Search component with debounced input\nfunction SearchBox() {\n  const [searchTerm, setSearchTerm] = useState('');\n  const debouncedSearchTerm = useDebounce(searchTerm, 500);\n  const [results, setResults] = useState([]);\n\n  useEffect(() => {\n    if (debouncedSearchTerm) {\n      fetch(`\u002Fapi\u002Fsearch?q=${debouncedSearchTerm}`)\n        .then(res => res.json())\n        .then(setResults);\n    }\n  }, [debouncedSearchTerm]);\n\n  return (\n    \u003Cinput\n      type=\"text\"\n      value={searchTerm}\n      onChange={(e) => setSearchTerm(e.target.value)}\n      placeholder=\"Search...\"\n    \u002F>\n  );\n}\n\n\u002F\u002F Manual debounce with useCallback (for function calls)\nfunction SearchButton() {\n  const handleSearch = useCallback(\n    debounce((query) => {\n      console.log('Searching for:', query);\n    }, 500),\n    []\n  );\n\n  return \u003Cbutton onClick={() => handleSearch('react')}>Search\u003C\u002Fbutton>;\n}\n\n\u002F\u002F Throttling scroll events\nfunction InfiniteScrollList() {\n  const [items, setItems] = useState([]);\n  const [page, setPage] = useState(1);\n  const throttleTimeout = useRef(null);\n\n  const handleScroll = useCallback(() => {\n    const scrollTop = document.documentElement.scrollTop;\n    const scrollHeight = document.documentElement.scrollHeight;\n    const clientHeight = document.documentElement.clientHeight;\n\n    if (scrollTop + clientHeight >= scrollHeight - 100) {\n      setPage(prev => prev + 1);\n    }\n  }, []);\n\n  const throttledScroll = useCallback(() => {\n    if (!throttleTimeout.current) {\n      throttleTimeout.current = setTimeout(() => {\n        handleScroll();\n        throttleTimeout.current = null;\n      }, 200);\n    }\n  }, [handleScroll]);\n\n  useEffect(() => {\n    window.addEventListener('scroll', throttledScroll);\n    return () => window.removeEventListener('scroll', throttledScroll);\n  }, [throttledScroll]);\n\n  useEffect(() => {\n    fetchItems(page).then(newItems => setItems(prev => [...prev, ...newItems]));\n  }, [page]);\n\n  return \u003Cdiv>{items.map(item => \u003Cdiv key={item.id}>{item.name}\u003C\u002Fdiv>)}\u003C\u002Fdiv>;\n}\n\n\u002F\u002F Utility functions\ndeclare function debounce\u003CT extends (...args: any[]) => any>(\n  fn: T,\n  delay: number\n): T & { cancel: () => void };\n\ndeclare function throttle\u003CT extends (...args: any[]) => any>(\n  fn: T,\n  limit: number\n): T;\n```\n\n**Execution Flow:**\n- Debounce: On each call, clear previous timer and set new one; only call after delay.\n- Throttle: Call immediately then prevent further calls until interval passes.\n\n**Reactivity Explanation:**\nThe debounced value hook uses `useEffect` to delay state updates; the component re-renders only when the debounced value changes.\n\n**Practical Usage:**\n- Debounce: search inputs, auto-save forms, window resize handlers.\n- Throttle: scroll events, game input, progress updates.\n\n**Common Mistakes:**\n- Not cleaning up timeouts in `useEffect` (memory leaks).\n- Using `debounce` inside render without `useCallback` (creates new timer on each render).\n- Expecting debounced function to be stable across renders (need `useCallback`).\n\n**Interview Follow-ups:**\n- What is the difference between debounce and throttle?\n- How do you test debounced functions in React?\n- What happens if you don't use `useCallback` with debounce?\n\n**Best Practices:**\n- Use custom hooks for debouncing\u002Fthrottling state values.\n- Use `lodash.debounce` or `lodash.throttle` with `useMemo`\u002F`useCallback`.\n- Cancel pending operations in cleanup.\n\n**Performance Considerations:**\n- Debouncing reduces expensive operations (API calls).\n- Throttling ensures scroll handlers don't block the main thread.\n\n**Production Recommendations:**\n- Use `lodash` for production debounce\u002Fthrottle (well-tested).\n- For search, also implement abort controller to cancel in-flight requests.\n- Use `requestAnimationFrame` for visual updates with throttle.\n\n**Node.js \u002F SSR Behavior:**\nDebounce\u002Fthrottle are client-side concepts; on server they are not needed.\n\n**Latest React Patterns:**\n- `useTransition` can be used for low-priority updates instead of debounce for UI responsiveness.\n- `useDeferredValue` can also delay rendering of non-critical UI.\n\n**TypeScript Example:**\n```tsx\nfunction useDebounce\u003CT>(value: T, delay: number): T {\n  const [debouncedValue, setDebouncedValue] = useState\u003CT>(value);\n  useEffect(() => {\n    const timer = setTimeout(() => setDebouncedValue(value), delay);\n    return () => clearTimeout(timer);\n  }, [value, delay]);\n  return debouncedValue;\n}\n```\n\n**Interview Tip:**\nExplain that debouncing and throttling are essential for performance, especially with expensive operations. In React, you must handle cleanup and stability.\n\n**Common Follow-up:**\n\"How do you cancel an API request when a new debounced search term comes?\" (Use AbortController in useEffect cleanup)\n\n**Real-world Example:**\nA real-time dashboard with live search: debouncing prevents API calls on every keystroke, saving server load and rate limits.\n\n**Advanced Notes:**\nLodash's debounce also has `maxWait` option to ensure function runs after some time even if events keep firing. You can implement debounced functions with `useRef` and `useCallback` for maximum control.",[293,294,182,47],"debounce","throttle",{"id":296,"category":175,"question":297,"answer":298,"level":213,"tags":299},37,"What is React.memo and how does it work? Explain when to use it and potential pitfalls.","**Concept Explanation:**\n`React.memo` is a higher-order component that memoizes a component, preventing unnecessary re-renders when its props have not changed. It performs a shallow comparison of props. If props are the same (by reference or shallow equality), the component is not re-rendered. It's a performance optimization, not a guarantee.\n\n**Syntax Explanation:**\n```jsx\nimport React, { memo } from 'react';\n\nconst MyComponent = memo(function MyComponent(props) {\n  \u002F\u002F only re-renders if props change\n});\n\n\u002F\u002F With custom comparison function\nconst MyComponent = memo(Component, (prevProps, nextProps) => {\n  return prevProps.id === nextProps.id; \u002F\u002F return true if no re-render needed\n});\n```\n\n**Code Example:**\n```jsx\nimport { memo, useState, useCallback } from 'react';\n\n\u002F\u002F Child component – re-renders only when name changes\nconst Child = memo(({ name, onClick }) => {\n  console.log('Child rendered');\n  return \u003Cbutton onClick={() => onClick(name)}>{name}\u003C\u002Fbutton>;\n});\n\nfunction Parent() {\n  const [count, setCount] = useState(0);\n  const [name, setName] = useState('Alice');\n\n  \u002F\u002F Without useCallback, this function would be new on every render,\n  \u002F\u002F causing Child to re-render even if name same\n  const handleClick = useCallback((name) => {\n    console.log(`Clicked ${name}`);\n  }, []);\n\n  return (\n    \u003Cdiv>\n      \u003Cp>Count: {count}\u003C\u002Fp>\n      \u003Cbutton onClick={() => setCount(c => c + 1)}>Increment\u003C\u002Fbutton>\n      \u003CChild name={name} onClick={handleClick} \u002F>\n    \u003C\u002Fdiv>\n  );\n}\n\n\u002F\u002F Memo with custom comparison\nconst Product = memo(\n  ({ product, onSelect }) => {\n    return \u003Cdiv onClick={() => onSelect(product.id)}>{product.name}\u003C\u002Fdiv>;\n  },\n  (prev, next) => prev.product.id === next.product.id && prev.product.price === next.product.price\n);\n\n\u002F\u002F Caveat: passing inline object as prop\nconst List = memo(({ items, style }) => {\n  return \u003Cdiv style={style}>{items.map(i => \u003Cspan key={i}>{i}\u003C\u002Fspan>)}\u003C\u002Fdiv>;\n});\n\nfunction App() {\n  const [count, setCount] = useState(0);\n  \u002F\u002F ❌ This style object is new every render – breaks memo\n  const style = { color: 'red' };\n  \u002F\u002F ✅ Solution: memoize style or define outside\n  const stableStyle = useMemo(() => ({ color: 'red' }), []);\n\n  return (\n    \u003Cdiv>\n      \u003Cbutton onClick={() => setCount(c => c + 1)}>Count: {count}\u003C\u002Fbutton>\n      \u003CList items={[1,2,3]} style={stableStyle} \u002F>\n    \u003C\u002Fdiv>\n  );\n}\n```\n\n**Execution Flow:**\n1. Parent renders, passing props to memoized child.\n2. React compares new props with previous props (shallow equal).\n3. If all props are equal (by `Object.is` comparison), React skips rendering the child.\n4. If any prop changed, child re-renders.\n\n**Reactivity Explanation:**\n`React.memo` is a performance optimization that can prevent child components from re-rendering when parent updates but child's props didn't change.\n\n**Practical Usage:**\n- Memoizing expensive components that render often.\n- Optimizing list items in large lists.\n- Preventing re-renders of pure presentational components.\n\n**Common Mistakes:**\n- Overusing `React.memo` on simple components (adds memory overhead).\n- Passing functions or objects that are re-created on each render (breaks memo).\n- Using `React.memo` without `useCallback` or `useMemo`.\n- Expecting memoization to work with children prop (children are new React elements each render).\n\n**Interview Follow-ups:**\n- What is the difference between `React.memo` and `useMemo`?\n- How does shallow comparison work? What about nested objects?\n- When should you not use `React.memo`?\n\n**Best Practices:**\n- Use `React.memo` only after profiling shows a performance problem.\n- Combine with `useCallback` and `useMemo` for stable props.\n- Provide custom comparison function for complex props.\n- Avoid memoizing components that always receive different props.\n\n**Performance Considerations:**\n- `React.memo` adds memory and comparison cost.\n- Useful for components that re-render often with same props (e.g., list items).\n- Not beneficial for components that almost always receive changed props.\n\n**Production Recommendations:**\n- Profile with React DevTools before adding memo.\n- Use `React.memo` for components in large lists.\n- For deeply nested objects, consider `useMemo` or restructuring data.\n\n**Node.js \u002F SSR Behavior:**\nWorks on server but server rendering doesn't have multiple render passes, so less benefit.\n\n**Latest React Patterns:**\n- React 19's React Compiler may auto-memoize, reducing need for manual `memo`.\n- `use` hook and React Server Components change memoization needs.\n\n**TypeScript Example:**\n```tsx\ninterface ProductProps {\n  product: { id: number; name: string };\n  onSelect: (id: number) => void;\n}\n\nconst Product = memo\u003CProductProps>(({ product, onSelect }) => {\n  return \u003Cdiv onClick={() => onSelect(product.id)}>{product.name}\u003C\u002Fdiv>;\n});\n```\n\n**Interview Tip:**\nExplain that `React.memo` is for component props; `useMemo` is for expensive computations. Emphasize that memoization is not free.\n\n**Common Follow-up:**\n\"What happens if you use `React.memo` but the component uses `useContext`?\" (Context changes still cause re-renders because the component subscribes to context)\n\n**Real-world Example:**\nA table with 1000 rows and a filter input. Without memo, all rows re-render on every keystroke. With `React.memo` on each row, only rows that change re-render.\n\n**Advanced Notes:**\n`React.memo` only checks prop changes. If the component uses `useState`, `useReducer`, or `useContext`, those can still cause re-renders even if props are equal. The custom comparison function can also be used to skip rendering based on specific fields.",[300,225,182],"react-memo",{"id":302,"category":58,"question":303,"answer":304,"level":213,"tags":305},38,"Explain the concept of compound components. How do you implement them using context and React.Children?","**Concept Explanation:**\nCompound components are a pattern where a parent component manages state and shares it with its children via context or `cloneElement`. Children are composed together to form a cohesive unit (e.g., `\u003CSelect>` with `\u003CSelect.Option>`). This pattern provides flexibility in rendering while maintaining implicit communication between components.\n\n**Syntax Explanation:**\n```jsx\n\u003CSelect value={value} onChange={setValue}>\n  \u003CSelect.Option value=\"apple\">Apple\u003C\u002FSelect.Option>\n  \u003CSelect.Option value=\"banana\">Banana\u003C\u002FSelect.Option>\n\u003C\u002FSelect>\n```\n\n**Code Example (Using Context):**\n```jsx\nimport { createContext, useContext, useState } from 'react';\n\n\u002F\u002F Context for sharing state\nconst TabsContext = createContext(null);\n\nfunction Tabs({ defaultIndex, children, onChange }) {\n  const [activeIndex, setActiveIndex] = useState(defaultIndex || 0);\n\n  const value = {\n    activeIndex,\n    setActiveIndex: (index) => {\n      setActiveIndex(index);\n      onChange?.(index);\n    },\n  };\n\n  return \u003CTabsContext.Provider value={value}>{children}\u003C\u002FTabsContext.Provider>;\n}\n\nfunction TabList({ children }) {\n  return \u003Cdiv className=\"tab-list\">{children}\u003C\u002Fdiv>;\n}\n\nfunction Tab({ index, children }) {\n  const { activeIndex, setActiveIndex } = useContext(TabsContext);\n  const isActive = activeIndex === index;\n\n  return (\n    \u003Cbutton\n      className={`tab ${isActive ? 'active' : ''}`}\n      onClick={() => setActiveIndex(index)}\n    >\n      {children}\n    \u003C\u002Fbutton>\n  );\n}\n\nfunction TabPanel({ index, children }) {\n  const { activeIndex } = useContext(TabsContext);\n  if (activeIndex !== index) return null;\n  return \u003Cdiv className=\"tab-panel\">{children}\u003C\u002Fdiv>;\n}\n\n\u002F\u002F Attach sub-components to parent for namespacing\nTabs.TabList = TabList;\nTabs.Tab = Tab;\nTabs.TabPanel = TabPanel;\n\n\u002F\u002F Usage\nfunction App() {\n  return (\n    \u003CTabs defaultIndex={0} onChange={(index) => console.log('Tab changed', index)}>\n      \u003CTabs.TabList>\n        \u003CTabs.Tab index={0}>Profile\u003C\u002FTabs.Tab>\n        \u003CTabs.Tab index={1}>Settings\u003C\u002FTabs.Tab>\n      \u003C\u002FTabs.TabList>\n      \u003CTabs.TabPanel index={0}>Profile content\u003C\u002FTabs.TabPanel>\n      \u003CTabs.TabPanel index={1}>Settings content\u003C\u002FTabs.TabPanel>\n    \u003C\u002FTabs>\n  );\n}\n\n\u002F\u002F Alternative using React.Children and cloneElement (for when context is too heavy)\nfunction Select({ children, value, onChange }) {\n  const enhancedChildren = React.Children.map(children, (child) => {\n    if (child.type === SelectOption) {\n      return React.cloneElement(child, {\n        selectedValue: value,\n        onSelect: onChange,\n      });\n    }\n    return child;\n  });\n  return \u003Cdiv className=\"select\">{enhancedChildren}\u003C\u002Fdiv>;\n}\n\nfunction SelectOption({ value, children, selectedValue, onSelect }) {\n  const isSelected = selectedValue === value;\n  return (\n    \u003Cdiv\n      className={`option ${isSelected ? 'selected' : ''}`}\n      onClick={() => onSelect(value)}\n    >\n      {children}\n    \u003C\u002Fdiv>\n  );\n}\n\nSelect.Option = SelectOption;\n```\n\n**Execution Flow:**\n1. Parent component (e.g., Tabs) sets up context state.\n2. Child components (Tab, TabPanel) consume context via `useContext`.\n3. When a child triggers state update, the parent state changes, causing all consumers to re-render.\n\n**Reactivity Explanation:**\nChanges in the parent's state are propagated to children through context, allowing them to react (e.g., show active tab).\n\n**Practical Usage:**\n- UI component libraries (tabs, accordions, dropdowns, menus).\n- Forms with shared validation state.\n- Wizards with step management.\n\n**Common Mistakes:**\n- Not handling missing context (provide helpful error messages).\n- Over-complicating simple composition with unnecessary context.\n- Forgetting to memoize context value to prevent unnecessary re-renders.\n\n**Interview Follow-ups:**\n- What is the advantage of compound components over prop drilling?\n- How do you ensure that children are only used within the parent?\n- What is the difference between compound components and render props?\n\n**Best Practices:**\n- Provide custom hook for consuming context with validation.\n- Document the required parent-child relationship.\n- Use `React.Children` map only when necessary (context is cleaner).\n- Attach sub-components as static properties for discoverability.\n\n**Performance Considerations:**\n- Context updates cause all child consumers to re-render. Consider splitting context for different data (e.g., value and callbacks).\n- `React.Children.map` runs on every render; keep it lightweight.\n\n**Production Recommendations:**\n- Use context-based compound components for flexibility.\n- Use TypeScript to enforce valid child structure.\n- Prefer context over cloneElement for better performance and React Server Component compatibility.\n\n**Node.js \u002F SSR Behavior:**\nWorks fine; context is part of the React tree on server.\n\n**Latest React Patterns:**\n- React 19 `use` hook may simplify context consumption.\n- Compound components work well with React Server Components (if they don't rely on client state).\n\n**TypeScript Example:**\n```tsx\ninterface TabsContextValue {\n  activeIndex: number;\n  setActiveIndex: (index: number) => void;\n}\n\nconst TabsContext = createContext\u003CTabsContextValue | null>(null);\n\nfunction useTabsContext() {\n  const context = useContext(TabsContext);\n  if (!context) throw new Error('useTabsContext must be used within Tabs');\n  return context;\n}\n```\n\n**Interview Tip:**\nExplain that compound components enable flexible, declarative APIs while hiding internal state management. They are common in design systems.\n\n**Common Follow-up:**\n\"How do you handle compound components when the children are nested deeper?\" (Context solves this naturally)\n\n**Real-world Example:**\nA `\u003CMenu>` component with `\u003CMenu.Item>`, `\u003CMenu.Submenu>`, `\u003CMenu.Divider>`. The Menu component tracks open state, highlighted item, and keyboard navigation.\n\n**Advanced Notes:**\nYou can combine compound components with `useImperativeHandle` to expose methods (e.g., reset). The pattern is also known as \"state provider\" pattern. React Bootstrap, Reach UI, and many libraries use compound components extensively.",[306,239,172],"compound-components",{"id":308,"category":109,"question":309,"answer":310,"level":213,"tags":311},39,"What is React Query (TanStack Query) and how does it solve common data fetching problems?","**Concept Explanation:**\nReact Query is a library for server state management. It handles caching, background refetching, stale-while-revalidate, request deduplication, pagination, infinite queries, mutation, and optimistic updates. It solves problems like loading\u002Ferror states, race conditions, caching strategies, and cache invalidation that are complex with raw `useEffect`.\n\n**Syntax Explanation:**\n```jsx\nimport { useQuery, useMutation } from '@tanstack\u002Freact-query';\n\nfunction Todos() {\n  const { data, isLoading, error } = useQuery({\n    queryKey: ['todos'],\n    queryFn: fetchTodos,\n  });\n}\n```\n\n**Code Example:**\n```jsx\nimport { QueryClient, QueryClientProvider, useQuery, useMutation, useQueryClient } from '@tanstack\u002Freact-query';\n\n\u002F\u002F Setup provider\nconst queryClient = new QueryClient();\nfunction App() {\n  return (\n    \u003CQueryClientProvider client={queryClient}>\n      \u003CTodoApp \u002F>\n    \u003C\u002FQueryClientProvider>\n  );\n}\n\n\u002F\u002F Query with parameters\nfunction TodoList({ userId }) {\n  const { data: todos, isLoading, error, refetch } = useQuery({\n    queryKey: ['todos', userId],\n    queryFn: () => fetchTodos(userId),\n    staleTime: 5 * 60 * 1000, \u002F\u002F Data considered fresh for 5 minutes\n    cacheTime: 10 * 60 * 1000, \u002F\u002F Cache persists for 10 minutes\n    retry: 3, \u002F\u002F Retry failed requests 3 times\n    refetchOnWindowFocus: true, \u002F\u002F Refetch when tab refocuses\n  });\n\n  if (isLoading) return \u003CSpinner \u002F>;\n  if (error) return \u003CError error={error} \u002F>;\n\n  return (\n    \u003Cdiv>\n      \u003Cbutton onClick={() => refetch()}>Refresh\u003C\u002Fbutton>\n      {todos.map(todo => \u003CTodo key={todo.id} todo={todo} \u002F>)}\n    \u003C\u002Fdiv>\n  );\n}\n\n\u002F\u002F Mutation with automatic cache update\nfunction AddTodo() {\n  const queryClient = useQueryClient();\n  const mutation = useMutation({\n    mutationFn: (newTodo) => axios.post('\u002Fapi\u002Ftodos', newTodo),\n    onSuccess: (data) => {\n      \u002F\u002F Invalidate and refetch\n      queryClient.invalidateQueries({ queryKey: ['todos'] });\n      \u002F\u002F Or update cache directly\n      queryClient.setQueryData(['todos'], (old) => [...old, data]);\n    },\n  });\n\n  return (\n    \u003Cbutton\n      onClick={() => mutation.mutate({ title: 'New Todo' })}\n      disabled={mutation.isPending}\n    >\n      {mutation.isPending ? 'Adding...' : 'Add Todo'}\n    \u003C\u002Fbutton>\n  );\n}\n\n\u002F\u002F Infinite queries for pagination\nfunction InfiniteFeed() {\n  const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfiniteQuery({\n    queryKey: ['feed'],\n    queryFn: ({ pageParam = 0 }) => fetchFeed(pageParam),\n    getNextPageParam: (lastPage) => lastPage.nextCursor,\n  });\n\n  return (\n    \u003Cdiv>\n      {data.pages.map(page => page.items.map(item => \u003Cdiv key={item.id}>{item.text}\u003C\u002Fdiv>))}\n      \u003Cbutton onClick={() => fetchNextPage()} disabled={!hasNextPage || isFetchingNextPage}>\n        Load More\n      \u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  );\n}\n```\n\n**Execution Flow:**\n1. Component calls `useQuery` with a query key and function.\n2. React Query checks cache for that key.\n3. If cached and fresh, returns data immediately.\n4. If stale or missing, fetches in background and updates cache.\n5. Returned data causes component re-render.\n6. Multiple components using same key share cached data and only one request is made.\n\n**Reactivity Explanation:**\nReact Query manages server state asynchronously, triggering re-renders when data arrives or cache updates. Query keys make the system reactive to parameter changes.\n\n**Practical Usage:**\n- REST API or GraphQL data fetching.\n- Paginated and infinite scroll lists.\n- Forms with optimistic updates.\n- Prefetching data on hover.\n\n**Common Mistakes:**\n- Using query keys that are not specific enough (over-fetching).\n- Not handling error states properly.\n- Forgetting to invalidate queries after mutations.\n- Using `useQuery` for mutations (use `useMutation`).\n\n**Interview Follow-ups:**\n- How does React Query handle request deduplication?\n- What is stale-while-revalidate strategy?\n- How do you implement optimistic updates?\n\n**Best Practices:**\n- Structure query keys as arrays for easy invalidation (`['todos', userId]`).\n- Set `staleTime` appropriately to reduce network requests.\n- Use `queryClient.setQueryData` for immediate UI updates (optimistic).\n- Use selectors to transform data only when needed.\n\n**Performance Considerations:**\n- React Query caches aggressively, reducing network load.\n- Background refetches happen after rendering, so UI stays responsive.\n- Cache size can be configured; default is reasonable.\n\n**Production Recommendations:**\n- Use React Query DevTools for debugging.\n- Configure global defaults via `QueryClient`.\n- Use `keepPreviousData` for pagination.\n- Implement `onError` for global error handling.\n\n**Node.js \u002F SSR Behavior:**\nReact Query supports SSR with `dehydrate`\u002F`hydrate` (Next.js, Remix).\n\n**Latest React Patterns:**\n- React Query v5 introduced major improvements (simplified API, better TypeScript).\n- Works with Suspense mode for data fetching.\n- Can be used alongside React Server Components.\n\n**TypeScript Example:**\n```tsx\ninterface Todo {\n  id: number;\n  title: string;\n}\n\nconst { data } = useQuery\u003CTodo[]>({\n  queryKey: ['todos'],\n  queryFn: fetchTodos,\n});\n```\n\n**Interview Tip:**\nExplain that React Query solves the 'server state' problem that raw `useEffect` cannot handle well: caching, race conditions, background updates, and synchronizing across components.\n\n**Common Follow-up:**\n\"How does React Query compare to Redux?\" (Different purposes: server state vs client state; can be used together)\n\n**Real-world Example:**\nA dashboard with multiple widgets, each fetching its own data. Without React Query, each widget would fetch independently, causing duplicate requests and complex caching. With React Query, all components share cache, deduplicate requests, and auto-refresh.\n\n**Advanced Notes:**\nReact Query also supports parallel queries, dependent queries (skip if condition not met), and prefetching. It integrates with WebSockets via `queryClient.setQueryData`. Mutation callbacks include `onMutate`, `onSuccess`, `onError`, `onSettled` for fine-grained control.",[115,113,312,313],"caching","tanstack",{"id":315,"category":58,"question":316,"answer":317,"level":213,"tags":318},40,"What is the difference between useEffect and useLayoutEffect? When would you use useLayoutEffect?","**Concept Explanation:**\n`useEffect` runs asynchronously after the browser has painted (non-blocking). `useLayoutEffect` runs synchronously immediately after React calculates DOM mutations but before the browser paints (blocking). Use `useLayoutEffect` when you need to read or write DOM layout and you want the changes to be applied before the user sees the screen (e.g., measure element size, avoid flickering).\n\n**Syntax Explanation:**\n```jsx\nuseEffect(() => {\n  \u002F\u002F Runs after paint – non-blocking\n}, [deps]);\n\nuseLayoutEffect(() => {\n  \u002F\u002F Runs before paint – blocking\n  return () => {}; \u002F\u002F cleanup runs before next layout effect\n}, [deps]);\n```\n\n**Code Example:**\n```jsx\nimport { useEffect, useLayoutEffect, useRef, useState } from 'react';\n\nfunction MeasureExample() {\n  const [height, setHeight] = useState(0);\n  const ref = useRef(null);\n\n  \u002F\u002F ❌ useEffect – may cause flicker (initial render shows 0, then updates)\n  useEffect(() => {\n    setHeight(ref.current.clientHeight);\n  }, []);\n\n  \u002F\u002F ✅ useLayoutEffect – measures before paint, no flicker\n  useLayoutEffect(() => {\n    setHeight(ref.current.clientHeight);\n  }, []);\n\n  return (\n    \u003Cdiv ref={ref}>\n      Height is: {height}px\n    \u003C\u002Fdiv>\n  );\n}\n\n\u002F\u002F Tooltip positioning\nfunction Tooltip({ targetRef, text }) {\n  const [position, setPosition] = useState({ top: 0, left: 0 });\n  const tooltipRef = useRef(null);\n\n  useLayoutEffect(() => {\n    if (targetRef.current && tooltipRef.current) {\n      const targetRect = targetRef.current.getBoundingClientRect();\n      const tooltipRect = tooltipRef.current.getBoundingClientRect();\n      setPosition({\n        top: targetRect.bottom + window.scrollY,\n        left: targetRect.left + window.scrollX - tooltipRect.width \u002F 2,\n      });\n    }\n  }, [targetRef, text]); \u002F\u002F Re-run when target or text changes\n\n  return (\n    \u003Cdiv\n      ref={tooltipRef}\n      style={{\n        position: 'absolute',\n        top: position.top,\n        left: position.left,\n      }}\n    >\n      {text}\n    \u003C\u002Fdiv>\n  );\n}\n\n\u002F\u002F Animation that must happen before paint\nfunction AnimatedComponent() {\n  const ref = useRef();\n\n  useLayoutEffect(() => {\n    ref.current.style.transform = 'translateX(100px)';\n    \u002F\u002F This change will be applied before browser paints\n    \u002F\u002F With useEffect, the element would initially render at 0, then jump\n  }, []);\n\n  return \u003Cdiv ref={ref}>Animated\u003C\u002Fdiv>;\n}\n```\n\n**Execution Flow:**\n1. Render phase: compute virtual DOM.\n2. React applies DOM mutations.\n3. **`useLayoutEffect` runs synchronously** (blocks paint).\n4. Browser paints (screen updated).\n5. `useEffect` runs asynchronously after paint.\n\n**Reactivity Explanation:**\nBoth hooks react to dependency changes. `useLayoutEffect` runs before paint, so synchronous state updates within it will be batched into the same paint.\n\n**Practical Usage:**\n- **useLayoutEffect:** Measuring DOM elements, synchronously adjusting layout to avoid flicker, scrolling to an element after render, tooltip positioning.\n- **useEffect:** Most side effects (data fetching, subscriptions, logging).\n\n**Common Mistakes:**\n- Using `useLayoutEffect` for data fetching (blocks paint unnecessarily).\n- Forgetting that `useLayoutEffect` runs on server (can cause warnings).\n- Overusing `useLayoutEffect` causing performance issues.\n\n**Interview Follow-ups:**\n- Why does `useLayoutEffect` cause warnings in SSR?\n- Can you use `useLayoutEffect` for animations? (Yes, but prefer `requestAnimationFrame`)\n- What happens if you update state inside `useLayoutEffect`?\n\n**Best Practices:**\n- Default to `useEffect` unless you have a specific need for pre-paint execution.\n- Use `useLayoutEffect` for DOM measurements and synchronous visual updates.\n- For SSR, provide fallback or use `useEffect` since `useLayoutEffect` warns.\n\n**Performance Considerations:**\n- `useLayoutEffect` blocks paint, delaying user seeing content.\n- Expensive calculations inside `useLayoutEffect` hurt perceived performance.\n- Use it sparingly, only when necessary.\n\n**Production Recommendations:**\n- Use `useLayoutEffect` in custom hooks that measure DOM (e.g., `useMeasure`).\n- For animations, use `requestAnimationFrame` or CSS transitions.\n- If you see SSR mismatch warnings, replace `useLayoutEffect` with `useEffect` on server.\n\n**Node.js \u002F SSR Behavior:**\n`useLayoutEffect` runs on server? In React 16\u002F17, it runs but with a warning. In React 18, it's suppressed and replaced with `useEffect` during SSR. Better to avoid or use conditional.\n\n**Latest React Patterns:**\n- React 19 may have improvements for layout effects in concurrent mode.\n- `useInsertionEffect` for CSS-in-JS (runs before `useLayoutEffect`).\n\n**TypeScript Example:**\n```tsx\nconst ref = useRef\u003CHTMLDivElement>(null);\nuseLayoutEffect(() => {\n  if (ref.current) {\n    const width = ref.current.clientWidth;\n    \u002F\u002F ...\n  }\n}, []);\n```\n\n**Interview Tip:**\nExplain the timing difference: `useEffect` after paint (non-blocking), `useLayoutEffect` before paint (blocking). Emphasize that most effects should be `useEffect`.\n\n**Common Follow-up:**\n\"How do you measure DOM element size without flicker?\" (Use `useLayoutEffect`)\n\n**Real-world Example:**\nA custom hook `useMeasure` that tracks an element's dimensions. Using `useLayoutEffect` ensures that the measurement is ready before the browser paints, avoiding layout shift.\n\n**Advanced Notes:**\n`useLayoutEffect` runs after React has committed the DOM changes but before the browser has painted. This makes it useful for integrating with non-React libraries that need to manipulate DOM after render. However, for data fetching, `useEffect` is the correct choice.",[88,319,89,157],"useLayoutEffect",{"id":321,"category":201,"question":322,"answer":323,"level":213,"tags":324},41,"How do you type React components, hooks, and events with TypeScript? Provide examples.","**Concept Explanation:**\nTypeScript provides static typing for React components, props, state, hooks, and events. Key types: `React.FC`, `React.ComponentProps`, `React.ComponentPropsWithoutRef`, event types (`React.ChangeEvent`, `React.MouseEvent`), hook generics (`useState\u003CT>`, `useRef\u003CT>`). This catches errors early and improves IDE autocomplete.\n\n**Syntax Explanation:**\n```tsx\n\u002F\u002F Component typing\ninterface ButtonProps {\n  label: string;\n  onClick: () => void;\n}\n\nconst Button: React.FC\u003CButtonProps> = ({ label, onClick }) => {\n  return \u003Cbutton onClick={onClick}>{label}\u003C\u002Fbutton>;\n};\n```\n\n**Code Example:**\n```tsx\nimport React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';\n\n\u002F\u002F 1. Component with children and optional props\ninterface CardProps {\n  title: string;\n  children: React.ReactNode;\n  onClose?: () => void;\n}\n\nconst Card: React.FC\u003CCardProps> = ({ title, children, onClose }) => {\n  return (\n    \u003Cdiv className=\"card\">\n      \u003Ch2>{title}\u003C\u002Fh2>\n      \u003Cdiv>{children}\u003C\u002Fdiv>\n      {onClose && \u003Cbutton onClick={onClose}>Close\u003C\u002Fbutton>}\n    \u003C\u002Fdiv>\n  );\n};\n\n\u002F\u002F 2. Typing state\nfunction Counter() {\n  const [count, setCount] = useState\u003Cnumber>(0);\n  const [user, setUser] = useState\u003C{ name: string; age: number } | null>(null);\n\n  useEffect(() => {\n    \u002F\u002F fetch user\n    setUser({ name: 'Alice', age: 30 });\n  }, []);\n\n  return \u003Cdiv>{count}\u003C\u002Fdiv>;\n}\n\n\u002F\u002F 3. Typing events\nfunction Form() {\n  const [value, setValue] = useState('');\n\n  const handleChange = (e: React.ChangeEvent\u003CHTMLInputElement>) => {\n    setValue(e.target.value);\n  };\n\n  const handleSubmit = (e: React.FormEvent\u003CHTMLFormElement>) => {\n    e.preventDefault();\n    console.log(value);\n  };\n\n  const handleClick = (e: React.MouseEvent\u003CHTMLButtonElement>) => {\n    e.stopPropagation();\n  };\n\n  const handleKeyDown = (e: React.KeyboardEvent\u003CHTMLInputElement>) => {\n    if (e.key === 'Enter') console.log('enter');\n  };\n\n  return (\n    \u003Cform onSubmit={handleSubmit}>\n      \u003Cinput value={value} onChange={handleChange} onKeyDown={handleKeyDown} \u002F>\n      \u003Cbutton onClick={handleClick}>Submit\u003C\u002Fbutton>\n    \u003C\u002Fform>\n  );\n}\n\n\u002F\u002F 4. Typing refs\nfunction FocusableInput() {\n  const inputRef = useRef\u003CHTMLInputElement>(null);\n\n  const focusInput = () => {\n    inputRef.current?.focus();\n  };\n\n  return \u003Cinput ref={inputRef} \u002F>;\n}\n\n\u002F\u002F 5. Typing hooks\nfunction useLocalStorage\u003CT>(key: string, initialValue: T): [T, (value: T) => void] {\n  const [storedValue, setStoredValue] = useState\u003CT>(() => {\n    const item = window.localStorage.getItem(key);\n    return item ? JSON.parse(item) : initialValue;\n  });\n\n  const setValue = (value: T) => {\n    setStoredValue(value);\n    window.localStorage.setItem(key, JSON.stringify(value));\n  };\n\n  return [storedValue, setValue];\n}\n\n\u002F\u002F 6. Generic components\ninterface ListProps\u003CT> {\n  items: T[];\n  renderItem: (item: T) => React.ReactNode;\n}\n\nfunction List\u003CT>({ items, renderItem }: ListProps\u003CT>) {\n  return \u003Cul>{items.map((item, i) => \u003Cli key={i}>{renderItem(item)}\u003C\u002Fli>)}\u003C\u002Ful>;\n}\n\n\u002F\u002F Usage\n\u003CList items={[{ name: 'Alice' }]} renderItem={(item) => item.name} \u002F>\n\n\u002F\u002F 7. forwardRef with types\ninterface InputProps extends React.InputHTMLAttributes\u003CHTMLInputElement> {\n  label?: string;\n}\n\nconst Input = React.forwardRef\u003CHTMLInputElement, InputProps>(({ label, ...props }, ref) => {\n  return (\n    \u003Cdiv>\n      {label && \u003Clabel>{label}\u003C\u002Flabel>}\n      \u003Cinput ref={ref} {...props} \u002F>\n    \u003C\u002Fdiv>\n  );\n});\n\n\u002F\u002F 8. ComponentProps utility\nfunction Button({ onClick, children }: React.ComponentProps\u003C'button'>) {\n  return \u003Cbutton onClick={onClick}>{children}\u003C\u002Fbutton>;\n}\n\n\u002F\u002F 9. Typing higher-order components\nfunction withLogger\u003CP extends object>(Component: React.ComponentType\u003CP>) {\n  return (props: P) => {\n    useEffect(() => console.log('Props:', props), [props]);\n    return \u003CComponent {...props} \u002F>;\n  };\n}\n\n\u002F\u002F 10. Discriminated unions for props\ninterface SuccessProps {\n  status: 'success';\n  data: string[];\n}\n\ninterface ErrorProps {\n  status: 'error';\n  error: Error;\n}\n\ntype AsyncComponentProps = SuccessProps | ErrorProps;\n\nfunction AsyncComponent({ status, ...props }: AsyncComponentProps) {\n  if (status === 'success') {\n    return \u003Cdiv>{props.data.join(', ')}\u003C\u002Fdiv>;\n  } else {\n    return \u003Cdiv>Error: {props.error.message}\u003C\u002Fdiv>;\n  }\n}\n```\n\n**Practical Usage:**\n- Define interfaces for all component props.\n- Use `React.FC` or explicit return type.\n- Use event types for callback parameters.\n- Use generics for reusable components and hooks.\n\n**Common Mistakes:**\n- Using `any` excessively (defeats type checking).\n- Forgetting to handle `null` or `undefined` for refs.\n- Not typing children properly (`React.ReactNode`).\n- Using `React.FC` with defaultProps (deprecated).\n\n**Interview Follow-ups:**\n- What is the difference between `React.FC` and typing props directly?\n- How do you type a component that accepts `...rest` props?\n- How do you type `useReducer`?\n\n**Best Practices:**\n- Prefer explicit `interface` for props over inline types.\n- Use `React.ComponentProps\u003C'element'>` to extend native elements.\n- Use `React.ReactNode` for children.\n- Use `unknown` instead of `any` with type guards.\n\n**Performance Considerations:**\n- TypeScript has zero runtime impact; types are erased.\n- Generic components may cause slower compile times but not runtime.\n\n**Production Recommendations:**\n- Enable strict mode in `tsconfig.json`.\n- Use `@types\u002Freact` and `@types\u002Freact-dom`.\n- Use `tsc --noEmit` in CI.\n\n**Node.js \u002F SSR Behavior:**\nTypes work identically on server and client.\n\n**Latest React Patterns:**\n- React 19 types include `React.CSSProperties` etc.\n- `satisfies` operator for stricter object literals.\n\n**Interview Tip:**\nShow practical examples of event typing and generic components. Emphasize that TypeScript prevents many runtime errors.\n\n**Common Follow-up:**\n\"How do you type a custom hook that returns a ref?\" (Return type `React.MutableRefObject\u003CT>`)\n\n**Real-world Example:**\nA component library with typed props ensures consumers get autocomplete and type errors when using the components incorrectly.\n\n**Advanced Notes:**\nYou can use `ComponentPropsWithRef` and `ComponentPropsWithoutRef` for forwardRef components. `ElementType` utility for polymorphic components. `React.PropsWithChildren` for adding children to existing props.",[205,206,28,47],{"id":326,"category":58,"question":327,"answer":328,"level":213,"tags":329},42,"Explain the concept of render props and how they compare to hooks for logic sharing.","**Concept Explanation:**\nRender props is a pattern where a component receives a function prop that returns a React element, allowing the component to share internal logic with its consumer. The component calls that function with internal state\u002Fdata, and the consumer decides what to render. This pattern predates hooks and is now mostly replaced by custom hooks for logic sharing.\n\n**Syntax Explanation:**\n```jsx\n\u002F\u002F Component that uses render prop\nfunction DataFetcher({ url, children }) {\n  const [data, setData] = useState(null);\n  useEffect(() => { fetch(url).then(setData); }, [url]);\n  return children(data);\n}\n\n\u002F\u002F Usage\n\u003CDataFetcher url=\"\u002Fapi\u002Fuser\">\n  {(data) => \u003Cdiv>{data?.name}\u003C\u002Fdiv>}\n\u003C\u002FDataFetcher>\n```\n\n**Code Example:**\n```jsx\n\u002F\u002F Mouse tracker with render prop\nclass MouseTracker extends React.Component {\n  state = { x: 0, y: 0 };\n  handleMove = (e) => this.setState({ x: e.clientX, y: e.clientY });\n  componentDidMount() { window.addEventListener('mousemove', this.handleMove); }\n  componentWillUnmount() { window.removeEventListener('mousemove', this.handleMove); }\n  render() { return this.props.children(this.state); }\n}\n\n\u002F\u002F Usage\n\u003CMouseTracker>\n  {({ x, y }) => \u003Cp>Mouse at {x}, {y}\u003C\u002Fp>}\n\u003C\u002FMouseTracker>\n\n\u002F\u002F Now with custom hook (modern approach)\nfunction useMouse() {\n  const [position, setPosition] = useState({ x: 0, y: 0 });\n  useEffect(() => {\n    const handler = (e) => setPosition({ x: e.clientX, y: e.clientY });\n    window.addEventListener('mousemove', handler);\n    return () => window.removeEventListener('mousemove', handler);\n  }, []);\n  return position;\n}\n\nfunction ComponentWithHook() {\n  const { x, y } = useMouse();\n  return \u003Cp>Mouse at {x}, {y}\u003C\u002Fp>;\n}\n\n\u002F\u002F Render prop with multiple arguments\nfunction FormState({ initialValues, children }) {\n  const [values, setValues] = useState(initialValues);\n  const handleChange = (e) => setValues({ ...values, [e.target.name]: e.target.value });\n  return children({ values, handleChange });\n}\n\n\u003CFormState initialValues={{ name: '' }}>\n  {({ values, handleChange }) => (\n    \u003Cinput name=\"name\" value={values.name} onChange={handleChange} \u002F>\n  )}\n\u003C\u002FFormState>\n\n\u002F\u002F Combining multiple render props (callback hell)\n\u003CMouseTracker>\n  {({ x, y }) => (\n    \u003CDataFetcher url={`\u002Fapi\u002Fcoordinates?x=${x}&y=${y}`}>\n      {(data) => (\n        \u003CThemeConsumer>\n          {(theme) => (\n            \u003Cdiv style={{ color: theme }}>\n              {data?.description}\n            \u003C\u002Fdiv>\n          )}\n        \u003C\u002FThemeConsumer>\n      )}\n    \u003C\u002FDataFetcher>\n  )}\n\u003C\u002FMouseTracker>\n\n\u002F\u002F Same with hooks (cleaner)\nfunction Combined() {\n  const { x, y } = useMouse();\n  const { data } = useFetch(`\u002Fapi\u002Fcoordinates?x=${x}&y=${y}`);\n  const { theme } = useTheme();\n  return \u003Cdiv style={{ color: theme }}>{data?.description}\u003C\u002Fdiv>;\n}\n```\n\n**Execution Flow:**\n- Render prop component encapsulates logic and calls the prop function with its internal state.\n- Consumer component defines how to render using that state.\n\n**Reactivity Explanation:**\nWhen the render prop component's internal state changes, it re-renders and calls the render function again, passing updated data.\n\n**Practical Usage:**\n- Sharing logic across components without inheritance.\n- Providing flexible rendering control to consumers.\n\n**Common Mistakes:**\n- Creating render props unnecessarily (use hooks).\n- Performance issues because inline functions can cause re-renders (mitigate with `useCallback`).\n- Prop drilling with render props (nested callbacks).\n\n**Interview Follow-ups:**\n- What are the advantages of render props over HOCs?\n- Why did hooks replace render props for most use cases?\n- How do you avoid nesting hell with render props?\n\n**Best Practices:**\n- Use `children` as a function for cleaner API.\n- Use `React.memo` to optimize if needed.\n- Prefer custom hooks for new code.\n\n**Performance Considerations:**\n- Render props create new functions on every render of parent, potentially causing child re-renders.\n- Hooks have less indirection and are more performant.\n\n**Production Recommendations:**\n- Use custom hooks for logic sharing in modern React.\n- Use render props only when you need to share rendering logic (e.g., component libraries providing layout control).\n\n**Node.js \u002F SSR Behavior:**\nWorks similarly; render props are functions called during render, so they execute on server as well.\n\n**Latest React Patterns:**\n- React Server Components cannot use hooks, but can use render props patterns.\n- Hooks have largely superseded render props and HOCs.\n\n**TypeScript Example:**\n```tsx\ninterface RenderPropProps\u003CT> {\n  data: T;\n  children: (data: T) => React.ReactNode;\n}\n\nfunction DataConsumer\u003CT>({ data, children }: RenderPropProps\u003CT>) {\n  return \u003C>{children(data)}\u003C\u002F>;\n}\n```\n\n**Interview Tip:**\nExplain that render props were a solution for logic reuse before hooks. Now, custom hooks are preferred because they are simpler, less nested, and more performant.\n\n**Common Follow-up:**\n\"Is there any case where render props are still better than hooks?\" (When you need to control rendering UI around the logic, e.g., `\u003CQuery>{(data) => ...}\u003C\u002FQuery>` – but React Query now uses hooks)\n\n**Real-world Example:**\nReact Router v5 used render props extensively (`\u003CRoute path=\"\u002F\" render={...} \u002F>`). React Router v6 switched to hooks (`useParams`, `useNavigate`).\n\n**Advanced Notes:**\nRender props can be combined with `React.Children.map` to inject props into children. The pattern is also known as \"function as children\" or \"function child component.\" It's still used in some libraries (e.g., `react-measure`).",[330,47,331],"render-props","logic-reuse",{"id":333,"category":175,"question":334,"answer":335,"level":213,"tags":336},43,"What is the virtual DOM? Explain the reconciliation algorithm and how React achieves efficient updates.","**Concept Explanation:**\nThe virtual DOM is a lightweight JavaScript representation of the actual DOM. React uses it to minimize direct DOM manipulations. When state changes, React creates a new virtual DOM tree, diffs it with the previous tree (reconciliation), calculates the minimal set of changes, and applies them to the real DOM in a batch (commit phase). This process is efficient due to heuristics and assumptions.\n\n**How Reconciliation Works:**\n1. **Different element types:** If root elements differ (e.g., `\u003Cdiv>` → `\u003Cspan>`), React tears down the old subtree and builds a new one.\n2. **Same element type:** React updates attributes\u002Fprops and recursively reconciles children.\n3. **List children with keys:** React uses keys to match items; without keys, falls back to index-based comparison.\n\n**Code Example (Simplified diff logic):**\n```jsx\n\u002F\u002F Before\n\u003Cdiv className=\"container\">\n  \u003Cp key=\"1\">First\u003C\u002Fp>\n  \u003Cp key=\"2\">Second\u003C\u002Fp>\n\u003C\u002Fdiv>\n\n\u002F\u002F After\n\u003Cdiv className=\"container\">\n  \u003Cp key=\"3\">Third\u003C\u002Fp>\n  \u003Cp key=\"1\">First\u003C\u002Fp>\n  \u003Cp key=\"2\">Second\u003C\u002Fp>\n\u003C\u002Fdiv>\n\n\u002F\u002F With keys, React knows:\n\u002F\u002F - Key \"3\" is new → insert\n\u002F\u002F - Keys \"1\" and \"2\" are moved → no re-render, just reposition\n\n\u002F\u002F Without keys, React would see:\n\u002F\u002F - First child changed from \u003Cp>First\u003C\u002Fp> to \u003Cp>Third\u003C\u002Fp> → update\n\u002F\u002F - Second child changed from \u003Cp>Second\u003C\u002Fp> to \u003Cp>First\u003C\u002Fp> → update\n\u002F\u002F - Third child added → insert\n\u002F\u002F Much more expensive!\n```\n\n**Execution Flow (React 18 Fiber):**\n1. **Render phase:** React builds a new fiber tree (virtual DOM) by calling component functions, diffing, and scheduling updates. This phase can be interrupted and prioritized.\n2. **Commit phase:** React applies the changes to the real DOM synchronously (cannot be interrupted).\n3. After commit, `useEffect` callbacks run.\n\n**Reactivity Explanation:**\nThe virtual DOM is the intermediary between state changes and actual DOM updates, enabling declarative UI programming.\n\n**Practical Usage:**\n- Developers never need to interact with virtual DOM directly; it's internal.\n- Provide `key` props to help reconciliation.\n- Use `React.memo` to skip diffing subtrees.\n\n**Common Mistakes:**\n- Using index as key when list order changes.\n- Changing component root type unnecessarily.\n- Not using `key` at all (React warns).\n\n**Interview Follow-ups:**\n- How does React compare virtual DOM to real DOM?\n- What is the time complexity of reconciliation? (O(n) due to heuristics)\n- Why does React need keys?\n\n**Best Practices:**\n- Always provide stable, unique keys for list items.\n- Keep component tree structure stable across renders.\n- Avoid unnecessary state updates that cause large tree diffs.\n\n**Performance Considerations:**\n- Virtual DOM diffing is fast but not free. Large lists without keys degrade performance.\n- React Fiber allows splitting work into chunks, keeping UI responsive.\n\n**Production Recommendations:**\n- Use React DevTools to profile re-renders and identify slow components.\n- Use `React.memo`, `useMemo`, and `useCallback` to reduce diffing scope.\n\n**Node.js \u002F SSR Behavior:**\nOn server, reconciliation is not needed because there is no DOM; only initial virtual DOM is generated and serialized to HTML.\n\n**Latest React Patterns:**\n- React 18's concurrent rendering allows reconciliation to be interrupted for high-priority updates (e.g., user input).\n- `useTransition` marks low-priority updates.\n\n**TypeScript Example:**\n(Not applicable)\n\n**Interview Tip:**\nExplain that the virtual DOM is a programming concept that enables declarative UI. Emphasize that it's not about being faster than manual DOM updates in all cases, but about predictability and maintainability.\n\n**Common Follow-up:**\n\"Is the virtual DOM the same as shadow DOM?\" (No, shadow DOM is a browser API for encapsulation)\n\n**Real-world Example:**\nA chat application with thousands of messages. Without keys, adding a new message would cause React to re-render all messages. With proper keys (`message.id`), React only inserts the new DOM node.\n\n**Advanced Notes:**\nReact Fiber's architecture uses a linked list traversal, allowing it to pause work, yield to the browser for higher priority tasks, and resume. This enables features like Suspense and concurrent rendering. The diffing algorithm is sometimes called \"reconciliation\" and is heavily optimized in production.",[13,136,337,182],"fiber",{"id":339,"category":340,"question":341,"answer":342,"level":213,"tags":343},44,"Testing","How do you test React components? Explain unit testing, integration testing, and tools like React Testing Library.","**Concept Explanation:**\nReact applications are typically tested with Jest as the test runner and React Testing Library (RTL) for rendering and interaction. RTL encourages testing the behavior as users experience it: querying by text, roles, and labels rather than internal implementation details. Tests include unit tests (isolated functions\u002F hooks), integration tests (component interactions), and end-to-end tests (full browser).\n\n**Syntax Explanation:**\n```jsx\nimport { render, screen, fireEvent } from '@testing-library\u002Freact';\nimport userEvent from '@testing-library\u002Fuser-event';\nimport Component from '.\u002FComponent';\n\ntest('button click updates text', async () => {\n  render(\u003CComponent \u002F>);\n  const button = screen.getByRole('button', { name: \u002Fclick me\u002Fi });\n  await userEvent.click(button);\n  expect(screen.getByText('Clicked')).toBeInTheDocument();\n});\n```\n\n**Code Example:**\n```jsx\n\u002F\u002F Component\nfunction Counter({ initialCount = 0 }) {\n  const [count, setCount] = useState(initialCount);\n  return (\n    \u003Cdiv>\n      \u003Cspan role=\"status\">Count: {count}\u003C\u002Fspan>\n      \u003Cbutton onClick={() => setCount(c => c + 1)}>Increment\u003C\u002Fbutton>\n      \u003Cbutton onClick={() => setCount(c => c - 1)}>Decrement\u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  );\n}\n\n\u002F\u002F Test\nimport { render, screen } from '@testing-library\u002Freact';\nimport userEvent from '@testing-library\u002Fuser-event';\nimport Counter from '.\u002FCounter';\n\ndescribe('Counter', () => {\n  test('renders initial count', () => {\n    render(\u003CCounter initialCount={5} \u002F>);\n    expect(screen.getByRole('status')).toHaveTextContent('Count: 5');\n  });\n\n  test('increments count when button clicked', async () => {\n    const user = userEvent.setup();\n    render(\u003CCounter \u002F>);\n    const incrementBtn = screen.getByRole('button', { name: \u002Fincrement\u002Fi });\n    await user.click(incrementBtn);\n    expect(screen.getByRole('status')).toHaveTextContent('Count: 1');\n  });\n\n  test('decrements count', async () => {\n    const user = userEvent.setup();\n    render(\u003CCounter \u002F>);\n    await user.click(screen.getByRole('button', { name: \u002Fdecrement\u002Fi }));\n    expect(screen.getByRole('status')).toHaveTextContent('Count: -1');\n  });\n});\n\n\u002F\u002F Testing async data fetching\nfunction UserProfile({ userId }) {\n  const [user, setUser] = useState(null);\n  useEffect(() => {\n    fetch(`\u002Fapi\u002Fusers\u002F${userId}`).then(res => res.json()).then(setUser);\n  }, [userId]);\n  if (!user) return \u003Cdiv>Loading...\u003C\u002Fdiv>;\n  return \u003Cdiv>Name: {user.name}\u003C\u002Fdiv>;\n}\n\n\u002F\u002F Test with mocked fetch\nimport { rest } from 'msw';\nimport { setupServer } from 'msw\u002Fnode';\n\nconst server = setupServer(\n  rest.get('\u002Fapi\u002Fusers\u002F1', (req, res, ctx) => {\n    return res(ctx.json({ name: 'Alice' }));\n  })\n);\n\nbeforeAll(() => server.listen());\nafterEach(() => server.resetHandlers());\nafterAll(() => server.close());\n\ntest('displays user data after fetch', async () => {\n  render(\u003CUserProfile userId={1} \u002F>);\n  expect(screen.getByText('Loading...')).toBeInTheDocument();\n  const nameElement = await screen.findByText('Name: Alice');\n  expect(nameElement).toBeInTheDocument();\n});\n\n\u002F\u002F Testing custom hooks\nimport { renderHook, act } from '@testing-library\u002Freact';\n\nfunction useCounter(initial = 0) {\n  const [count, setCount] = useState(initial);\n  const increment = () => setCount(c => c + 1);\n  return { count, increment };\n}\n\ntest('useCounter increments', () => {\n  const { result } = renderHook(() => useCounter(5));\n  expect(result.current.count).toBe(5);\n  act(() => result.current.increment());\n  expect(result.current.count).toBe(6);\n});\n```\n\n**Practical Usage:**\n- Unit: test pure functions, custom hooks, utilities.\n- Integration: test component interactions, forms, API calls.\n- E2E: Cypress or Playwright for full user journeys.\n\n**Common Mistakes:**\n- Testing implementation details (state, props, internal methods).\n- Not using `await` for async events.\n- Not cleaning up side effects between tests.\n- Forgetting to wrap act for state updates.\n\n**Interview Follow-ups:**\n- Why does React Testing Library discourage testing implementation details?\n- How do you test a component that uses React Router?\n- What is the difference between `fireEvent` and `userEvent`?\n\n**Best Practices:**\n- Query by role, text, or test ID (data-testid) as last resort.\n- Use `userEvent` over `fireEvent` for realistic interactions.\n- Test behavior that users care about.\n- Mock external APIs (MSW recommended).\n\n**Performance Considerations:**\n- Keep tests isolated and fast.\n- Use `jest.mock` for module mocks.\n- Use `waitFor` for async expectations.\n\n**Production Recommendations:**\n- Set up Continuous Integration to run tests.\n- Use coverage thresholds.\n- Write tests alongside components (colocation).\n\n**Node.js \u002F SSR Behavior:**\nTests run in Node environment (JSDOM simulates browser). For SSR-specific tests, use frameworks like Next.js testing utilities.\n\n**Latest React Patterns:**\n- React 18's concurrent rendering may require wrapping updates in `act` more often.\n- `@testing-library\u002Freact` has updated APIs for React 18.\n\n**TypeScript Example:**\n```tsx\nimport { render, screen } from '@testing-library\u002Freact';\nimport MyComponent from '.\u002FMyComponent';\n\ntest('renders correctly', () => {\n  render(\u003CMyComponent name=\"Test\" \u002F>);\n  const element = screen.getByText(\u002FTest\u002F);\n  expect(element).toBeInTheDocument();\n});\n```\n\n**Interview Tip:**\nExplain that the goal is to test the component as a user would, not its internal implementation. This makes tests more resilient to refactoring.\n\n**Common Follow-up:**\n\"How do you test components that depend on context providers?\" (Wrap with provider in test, or create a custom render function)\n\n**Real-world Example:**\nA login form: test that entering credentials and clicking submit calls the onSubmit handler, and that error messages appear on invalid input.\n\n**Advanced Notes:**\n`@testing-library\u002Freact` v14+ requires React 18. Use `screen` for queries. `jest` can be configured with `@testing-library\u002Fjest-dom` for custom matchers. For snapshot testing, use sparingly (can be brittle).",[344,345,346,347],"testing","jest","react-testing-library","unit-test",{"id":349,"category":350,"question":351,"answer":352,"level":213,"tags":353},45,"Architecture","What are the best practices for organizing a large React application? Discuss folder structure, component patterns, and state management.","**Concept Explanation:**\nOrganizing large React applications requires separation of concerns, scalability, and team collaboration. Common patterns: feature-based folders (grouping by domain), component composition, state management strategy (local, context, external store), API layer abstraction, and custom hooks for logic reuse. Consistency and clear boundaries are key.\n\n**Folder Structure Example:**\n```\nsrc\u002F\n├── features\u002F          # Feature-based modules\n│   ├── auth\u002F\n│   │   ├── components\u002F   # Feature-specific components\n│   │   ├── hooks\u002F        # Feature-specific hooks\n│   │   ├── api\u002F          # API calls for this feature\n│   │   ├── types\u002F        # TS types\u002Finterfaces\n│   │   └── index.ts      # Public API\n│   ├── dashboard\u002F\n│   └── products\u002F\n├── shared\u002F            # Reusable across features\n│   ├── ui\u002F            # Buttons, modals, cards\n│   ├── hooks\u002F         # useLocalStorage, useDebounce\n│   ├── utils\u002F         # helpers, formatters\n│   ├── api\u002F           # axios instance, interceptors\n│   └── types\u002F         # Global types\n├── app\u002F               # App-level setup\n│   ├── store\u002F         # Redux\u002FZustand store\n│   ├── routes\u002F        # Routing configuration\n│   └── providers\u002F     # Theme, Query, Context providers\n├── assets\u002F            # Images, fonts\n└── main.tsx\n```\n\n**Component Patterns:**\n```tsx\n\u002F\u002F 1. Container \u002F Presentational pattern (with hooks)\n\u002F\u002F ProductList.tsx (container)\nfunction ProductList() {\n  const { products, loading, error } = useProducts();\n  if (loading) return \u003CSpinner \u002F>;\n  if (error) return \u003CErrorMessage error={error} \u002F>;\n  return \u003CProductListView products={products} \u002F>;\n}\n\n\u002F\u002F ProductListView.tsx (presentational)\nfunction ProductListView({ products }) {\n  return \u003Cul>{products.map(p => \u003CProductItem key={p.id} product={p} \u002F>)}\u003C\u002Ful>;\n}\n\n\u002F\u002F 2. Compound components (e.g., Tabs)\n\u002F\u002F 3. Higher-order components (avoid, prefer hooks)\n\u002F\u002F 4. Custom hooks for logic\n```\n\n**State Management Strategy:**\n- **Local state:** `useState`, `useReducer` for component-only state.\n- **Shared state:** Context API for low-frequency, global-ish data (theme, auth).\n- **Server state:** React Query, SWR for API data (caching, background sync).\n- **Complex global state:** Zustand, Redux Toolkit, Jotai for app-wide client state.\n\n**API Layer Abstraction:**\n```tsx\n\u002F\u002F api\u002Fclient.ts\nimport axios from 'axios';\n\nexport const apiClient = axios.create({\n  baseURL: import.meta.env.VITE_API_URL,\n  timeout: 10000,\n});\n\napiClient.interceptors.request.use((config) => {\n  const token = localStorage.getItem('token');\n  if (token) config.headers.Authorization = `Bearer ${token}`;\n  return config;\n});\n\n\u002F\u002F features\u002Fproducts\u002Fapi.ts\nimport { apiClient } from '@\u002Fshared\u002Fapi\u002Fclient';\n\nexport const productApi = {\n  getProducts: () => apiClient.get('\u002Fproducts').then(res => res.data),\n  createProduct: (data) => apiClient.post('\u002Fproducts', data),\n};\n```\n\n**Code Example (Feature module):**\n```tsx\n\u002F\u002F features\u002Fproducts\u002Fhooks\u002FuseProducts.ts\nimport { useQuery } from '@tanstack\u002Freact-query';\nimport { productApi } from '..\u002Fapi';\n\nexport function useProducts() {\n  return useQuery({\n    queryKey: ['products'],\n    queryFn: productApi.getProducts,\n  });\n}\n\n\u002F\u002F features\u002Fproducts\u002Fcomponents\u002FProductCard.tsx\nexport function ProductCard({ product }) {\n  return \u003Cdiv>{product.name}\u003C\u002Fdiv>;\n}\n\n\u002F\u002F features\u002Fproducts\u002Findex.ts (public API)\nexport { ProductList } from '.\u002Fcomponents\u002FProductList';\nexport { useProducts } from '.\u002Fhooks\u002FuseProducts';\nexport type { Product } from '.\u002Ftypes';\n```\n\n**Practical Usage:**\n- Organize by features, not by file types (avoid `components\u002F`, `containers\u002F`, `hooks\u002F` top-level).\n- Use `barrel exports` (index.ts) to control public API.\n- Colocate tests with components.\n\n**Common Mistakes:**\n- Over-engineering folder structure too early.\n- Circular dependencies between features.\n- Not having a clear boundary between shared and feature code.\n- Putting all state in global store.\n\n**Interview Follow-ups:**\n- How do you decide between putting code in `shared` vs `features`?\n- What is the role of index.ts files?\n- How do you handle cross-feature dependencies?\n\n**Best Practices:**\n- Keep features independent (can be removed without breaking others).\n- Use absolute imports (`@\u002Ffeatures\u002Fauth`).\n- Prefer custom hooks over HOCs or render props.\n- Use TypeScript for better refactoring.\n\n**Performance Considerations:**\n- Lazy load features with `React.lazy` for code splitting.\n- Feature-based structure aligns well with dynamic imports.\n\n**Production Recommendations:**\n- Use tools like Nx or Turborepo for monorepo.\n- Enforce folder structure with ESLint rules.\n- Document architecture decisions.\n\n**Node.js \u002F SSR Behavior:**\nFor Next.js, follow its folder conventions (`app\u002F`, `components\u002F`, `lib\u002F`).\n\n**Latest React Patterns:**\n- React Server Components change organization (client vs server components).\n- Feature slicing methodology (from Frontend Architecture).\n\n**TypeScript Example:**\n```tsx\n\u002F\u002F Shared types\nexport interface ApiResponse\u003CT> {\n  data: T;\n  status: number;\n}\n```\n\n**Interview Tip:**\nEmphasize that the goal is to make the codebase predictable and scalable. Feature-based structure is generally preferred over technical grouping.\n\n**Common Follow-up:**\n\"How do you handle shared state across features without coupling?\" (Use a dedicated state module (store) and import it, or use React Context in the app root)\n\n**Real-world Example:**\nAn e-commerce app with features: product catalog, cart, checkout, user account. Each feature has its own components, hooks, and API logic, but they share UI components and auth context.\n\n**Advanced Notes:**\nModule Federation (Webpack 5) allows multiple teams to deploy separate feature modules independently. Micro-frontend architecture can extend this pattern across repositories. Linting rules can enforce import boundaries (e.g., no importing from `features\u002Fcart` into `features\u002Fproducts`).",[354,355,241,356],"architecture","folder-structure","scaling",[358,368,377,384,391,398,408,414,421,428,436,443,453,461,466,472,480,488,495,503],{"id":359,"category":360,"question":361,"answer":362,"level":363,"tags":364},46,"React Internals","Explain React Fiber architecture. How does it enable concurrent rendering and what are the benefits?","**Concept Explanation:**\nReact Fiber is a complete rewrite of React's reconciliation algorithm (React 16+). It breaks rendering work into units (fibers) that can be prioritized, paused, resumed, and aborted. Fiber enables concurrent rendering: React can work on multiple updates, interrupt low-priority work for high-priority user input, and yield to the browser to prevent jank.\n\n**How It Works:**\n- **Fiber node:** Each React element becomes a fiber node with type, key, props, state, and a linked list structure (child, sibling, return).\n- **Two phases:**\n  - **Render\u002FReconciliation phase:** Work is done asynchronously, can be interrupted. Builds a fiber tree and marks side effects.\n  - **Commit phase:** Synchronous, applies DOM mutations (cannot be interrupted).\n- **Scheduler:** Prioritizes work types (Immediate, UserBlocking, Normal, Low, Idle). Uses `requestIdleCallback` polyfill and message channel.\n\n**Code Example (Conceptual):**\n```jsx\n\u002F\u002F Work loop pseudocode\nfunction workLoop(deadline) {\n  let shouldYield = false;\n  while (nextUnitOfWork && !shouldYield) {\n    nextUnitOfWork = performUnitOfWork(nextUnitOfWork);\n    shouldYield = deadline.timeRemaining() \u003C 1;\n  }\n  if (nextUnitOfWork) requestIdleCallback(workLoop);\n}\n```\n\n**Execution Flow:**\n1. `setState` or `render` creates an update.\n2. React schedules work with a priority.\n3. In render phase, React traverses fiber tree, computes effects, yields to browser when needed.\n4. Commit phase flushes changes synchronously to DOM.\n\n**Reactivity Explanation:**\nFiber allows React to respond to user input immediately by interrupting lower-priority reconciliation work.\n\n**Practical Usage:**\n- Developers rarely interact with Fiber directly, but benefit from smoother UIs.\n- `useTransition` and `useDeferredValue` expose priority control.\n\n**Common Mistakes:**\n- Assuming all updates are synchronous (React 18 batches more).\n- Not using `startTransition` for expensive updates.\n\n**Interview Follow-ups:**\n- What is the difference between the render phase and commit phase?\n- How does Fiber prevent jank?\n- What are side effects in Fiber?\n\n**Best Practices:**\n- Use `startTransition` for non-urgent state updates.\n- Use `useDeferredValue` to defer rendering of slow parts.\n\n**Performance Considerations:**\n- Concurrent rendering improves responsiveness but adds overhead.\n- Too many high-priority updates can still starve low-priority work.\n\n**Production Recommendations:**\n- Update to React 18+ to leverage concurrent features.\n- Profile with React DevTools to identify slow components.\n\n**Node.js \u002F SSR Behavior:**\nFiber is client-only; server rendering is synchronous.\n\n**Latest React Patterns:**\n- React 18 `createRoot` enables concurrent features by default.\n- Suspense for data fetching relies on Fiber.\n\n**TypeScript Example:**\n(Not applicable – internal implementation)\n\n**Interview Tip:**\nExplain that Fiber is not about performance but about scheduling and responsiveness. It allows React to work on multiple updates incrementally.\n\n**Common Follow-up:**\n\"How does React decide which updates have higher priority?\" (Based on event type: click\u002Finput are high, data fetching lower)\n\n**Real-world Example:**\nA search input that filters a large list. Without concurrent rendering, typing may lag because list filtering blocks the thread. With Fiber, typing has high priority, list filtering yields, keeping UI responsive.\n\n**Advanced Notes:**\nFiber uses a double-buffering technique (current and work-in-progress trees). The scheduler implements a priority queue. `reconciliation` is now interruptible. React 18 also adds automatic batching, which builds on Fiber capabilities.","advanced",[337,365,366,367],"concurrent-rendering","react-internals","scheduling",{"id":369,"category":360,"question":370,"answer":371,"level":363,"tags":372},47,"How does the React Scheduler work? Explain priorities, time slicing, and how it integrates with the event loop.","**Concept Explanation:**\nReact Scheduler is an internal module that manages task priorities and time slicing. It works by breaking rendering work into chunks and yielding to the browser using `postMessage` or `MessageChannel`. Tasks have priorities (Immediate, UserBlocking, Normal, Low, Idle). The scheduler interacts with the browser's event loop, ensuring high-priority tasks (like user input) execute before lower-priority background updates.\n\n**How It Works:**\n- Each update is assigned a priority based on user interaction type.\n- Scheduler maintains a min-heap of tasks.\n- Work loop continuously runs: process tasks until time slice expires, then yields.\n- Uses `MessageChannel` to schedule a callback in the next macrotask.\n\n**Code Example (Conceptual):**\n```jsx\n\u002F\u002F Simplified scheduler\nconst tasks = [];\nlet isPerformingWork = false;\n\nfunction scheduleTask(priority, callback) {\n  tasks.push({ priority, callback });\n  if (!isPerformingWork) requestHostCallback(workLoop);\n}\n\nfunction workLoop(deadline) {\n  let currentTask = tasks.pop();\n  while (currentTask && deadline.timeRemaining() > 0) {\n    currentTask.callback();\n    currentTask = tasks.pop();\n  }\n  if (tasks.length) requestHostCallback(workLoop);\n}\n```\n\n**Execution Flow:**\n1. User clicks button → React schedules update with `UserBlockingPriority`.\n2. Another large list update scheduled with `NormalPriority`.\n3. Scheduler runs high-priority task first, may interrupt low-priority.\n4. After time slice (5ms), yields to browser for paint\u002Finput.\n5. Resumes remaining work.\n\n**Reactivity Explanation:**\nThe scheduler makes React \"reactive\" to user needs by prioritizing interactions.\n\n**Practical Usage:**\n- Developers use `startTransition` to mark non-urgent updates as Low priority.\n- `useDeferredValue` uses Scheduler to defer re-renders.\n\n**Common Mistakes:**\n- Wrapping everything in `startTransition` (unnecessary).\n- Expecting immediate UI updates after transition.\n\n**Interview Follow-ups:**\n- How does React measure time remaining?\n- What happens if a task exceeds its time slice?\n- How does the scheduler differ from `requestIdleCallback`?\n\n**Best Practices:**\n- Use `startTransition` for expensive filtering, chart updates.\n- Avoid transitions for critical UI (buttons, forms).\n\n**Performance Considerations:**\n- Time slicing adds overhead; not needed for small updates.\n- Excessive transitions can cause UI delay.\n\n**Production Recommendations:**\n- Enable concurrent features via `createRoot`.\n- Use React DevTools to visualize task priorities.\n\n**Node.js \u002F SSR Behavior:**\nScheduler is not used on server; all work is synchronous.\n\n**Latest React Patterns:**\n- React 18 stable concurrent rendering.\n- `useTransition` includes `isPending` flag.\n\n**TypeScript Example:**\n```tsx\nconst [isPending, startTransition] = useTransition();\nstartTransition(() => setFilter(value));\n```\n\n**Interview Tip:**\nExplain that the scheduler is the core behind concurrent features, enabling React to be \"non-blocking.\"\n\n**Common Follow-up:**\n\"What is the default time slice?\" (~5ms, but dynamically adjusts)\n\n**Real-world Example:**\nA map application with thousands of markers. User panning (high priority) should feel smooth, while marker rendering (low priority) yields.\n\n**Advanced Notes:**\nReact polyfills `requestIdleCallback` with `MessageChannel` and `setTimeout`. The scheduler also includes a `shouldYield` check to avoid starving the main thread. Priorities are translated from React event priorities to scheduler priorities.",[373,374,375,376],"scheduler","concurrency","priorities","event-loop",{"id":378,"category":58,"question":379,"answer":380,"level":363,"tags":381},48,"Explain the commit phase and render phase in React reconciliation. What happens in each and why are they separate?","**Concept Explanation:**\nReact reconciliation is split into two distinct phases: render phase and commit phase. The **render phase** is asynchronous, interruptible, and computes what changes are needed (by building the effect list). The **commit phase** is synchronous, uninterruptible, and applies those changes to the DOM. Separating them allows React to pause, abort, or prioritize work without causing inconsistent UI states.\n\n**Render Phase (also called \"Reconciliation\"):**\n- Creates a new fiber tree (work-in-progress) by diffing.\n- Calls component functions (or `render` methods) for functional components.\n- Collects side effects (DOM updates, lifecycle callbacks) into an effect list.\n- Can be paused, split, or aborted.\n- Does not touch the DOM.\n\n**Commit Phase:**\n- Takes the effect list from render phase.\n- Applies DOM mutations (insert, update, delete) synchronously.\n- Calls `useLayoutEffect` cleanups and then `useLayoutEffect` callbacks (before paint).\n- After paint, calls `useEffect` callbacks.\n- Cannot be interrupted.\n\n**Code Example (Conceptual):**\n```jsx\n\u002F\u002F Render phase – may be interrupted\nexport const renderPhase = (fiber) => {\n  const children = fiber.type(fiber.props); \u002F\u002F may call component\n  reconcileChildren(fiber, children);\n  return fiber.child;\n};\n\n\u002F\u002F Commit phase – synchronous\nexport const commitPhase = (fiber) => {\n  switch (fiber.effectTag) {\n    case 'PLACEMENT': insertNode(fiber.stateNode); break;\n    case 'UPDATE': updateNode(fiber.stateNode, fiber.updateQueue); break;\n    case 'DELETION': deleteNode(fiber.stateNode); break;\n  }\n};\n```\n\n**Execution Flow:**\n1. User clicks → schedule update.\n2. Render phase: start building work-in-progress tree; if user clicks again, interrupt and start new update.\n3. Render phase completes → effect list ready.\n4. Commit phase: flush DOM updates (user sees change).\n5. Then `useEffect` runs after paint.\n\n**Reactivity Explanation:**\nThe separation allows React to render multiple versions of the tree in memory and commit the final one, preventing partial UI updates.\n\n**Practical Usage:**\n- Developers don't directly interact but see benefits: smoother interactions, Suspense.\n- `useLayoutEffect` runs in commit phase before paint.\n- `useEffect` runs after commit phase (post-paint).\n\n**Common Mistakes:**\n- Performing side effects in render phase (e.g., state updates, DOM writes).\n- Expecting `useEffect` to run synchronously after state change.\n\n**Interview Follow-ups:**\n- Why can't `useLayoutEffect` be deferred?\n- What happens if a side effect occurs during render phase?\n- How does Suspense use the render phase?\n\n**Best Practices:**\n- Keep render phase pure (no side effects).\n- Use `useEffect` for side effects, `useLayoutEffect` for DOM measurements.\n\n**Performance Considerations:**\n- Long render phases can delay commit; break work with transitions.\n- Heavy `useLayoutEffect` blocks paint.\n\n**Production Recommendations:**\n- Profile with React DevTools to see phase timing.\n- Avoid synchronous work in render (e.g., expensive calculations).\n\n**Node.js \u002F SSR Behavior:**\nSSR only has render phase (to string), no commit phase (no DOM).\n\n**Latest React Patterns:**\n- React 18's concurrent rendering can pause render phase.\n- Offscreen API (future) may use render phase without commit.\n\n**TypeScript Example:**\n(Not applicable)\n\n**Interview Tip:**\nUse an analogy: render phase = planning (can be interrupted), commit phase = building (must finish).\n\n**Common Follow-up:**\n\"Does `useEffect` run in commit phase?\" (No, after commit phase, after paint)\n\n**Real-world Example:**\nA slow component tree. With concurrent features, React can pause rendering to handle a click, then resume. The user never sees a half-rendered UI because commit is atomic.\n\n**Advanced Notes:**\nThe render phase also handles `getDerivedStateFromProps` and `shouldComponentUpdate`. Effect list is a linked list of fibers with side effects. The commit phase also calls ref callbacks. React 18's `useSyncExternalStore` ensures external store consistency during concurrent rendering.",[382,383,136,337],"render-phase","commit-phase",{"id":385,"category":360,"question":386,"answer":387,"level":363,"tags":388},49,"How does React handle automatic batching and when does it batch updates? Compare React 17 vs 18.","**Concept Explanation:**\nBatching is React's technique of grouping multiple state updates into a single re-render to improve performance. React 17 batched updates only inside browser event handlers (e.g., onClick). React 18 introduced automatic batching for all updates regardless of origin (promises, setTimeout, native event handlers, etc.), reducing unnecessary renders.\n\n**How It Works:**\n- React wraps callbacks in an internal `batchedUpdates` function.\n- It tracks whether batching is enabled via a global variable.\n- In React 18, `createRoot` enables automatic batching by default.\n- You can opt out with `flushSync`.\n\n**Code Example:**\n```jsx\n\u002F\u002F React 17 – only batches inside React events\nfunction Component() {\n  const [a, setA] = useState(0);\n  const [b, setB] = useState(0);\n\n  const handleClick = () => {\n    setA(1); \u002F\u002F batch -> one re-render\n    setB(2);\n  };\n\n  const handleAsync = () => {\n    setTimeout(() => {\n      setA(1); \u002F\u002F React 17: two re-renders\n      setB(2); \u002F\u002F React 18: batched (one re-render)\n    }, 100);\n  };\n\n  return \u003Cbutton onClick={handleAsync}>Click\u003C\u002Fbutton>;\n}\n\n\u002F\u002F React 18 automatic batching\nimport { flushSync } from 'react-dom';\n\nfunction Component() {\n  const [count, setCount] = useState(0);\n  const [flag, setFlag] = useState(false);\n\n  const handleUpdate = () => {\n    \u002F\u002F All these are batched together\n    fetchSomething().then(() => {\n      setCount(c => c + 1);\n      setFlag(f => !f);\n      \u002F\u002F Only one re-render\n    });\n  };\n\n  const handleFlushSync = () => {\n    flushSync(() => setCount(1)); \u002F\u002F forces immediate render\n    \u002F\u002F DOM updated before next line\n    setFlag(true); \u002F\u002F another render\n  };\n}\n```\n\n**Execution Flow:**\n1. Event or async callback triggers.\n2. React enables batching mode.\n3. Multiple setState calls are queued.\n4. After callback finishes, React performs a single re-render.\n5. In React 17, only callbacks from event system are batched; others cause immediate re-renders.\n\n**Reactivity Explanation:**\nBatching reduces reactivity churn, making apps faster.\n\n**Practical Usage:**\n- Developers can write multiple state updates without worrying about performance.\n- Use `flushSync` only when you need synchronous DOM reads after update.\n\n**Common Mistakes:**\n- Relying on batching for timing (e.g., expecting DOM update after first setState).\n- Using `flushSync` unnecessarily (defeats batching benefits).\n\n**Interview Follow-ups:**\n- Why doesn't React batch updates across multiple async callbacks?\n- How does `flushSync` affect performance?\n- Can you disable automatic batching in React 18?\n\n**Best Practices:**\n- Let React handle batching; avoid `flushSync` unless required.\n- Group state updates naturally; extra batching is automatic.\n\n**Performance Considerations:**\n- Automatic batching reduces re-renders, improving performance.\n- `flushSync` forces synchronous re-render, may cause jank.\n\n**Production Recommendations:**\n- Use `createRoot` to enable automatic batching.\n- For React 17 or older, manually batch with `unstable_batchedUpdates`.\n\n**Node.js \u002F SSR Behavior:**\nBatching is client-only; server renders once per request.\n\n**Latest React Patterns:**\n- React 18's `useSyncExternalStore` works with batching.\n- `startTransition` also batches updates.\n\n**TypeScript Example:**\n```tsx\nimport { flushSync } from 'react-dom';\n\nflushSync(() => setState(newValue));\n```\n\n**Interview Tip:**\nExplain that automatic batching means fewer renders and predictable behavior across environments.\n\n**Common Follow-up:**\n\"Does `ReactDOM.render` in React 18 support automatic batching?\" (No, only `createRoot`)\n\n**Real-world Example:**\nForm with multiple validation fields that update on blur. In React 17, each field update could cause separate re-renders. In React 18, they batch.\n\n**Advanced Notes:**\nReact's batching is implemented via `executeDispatchesInOrder` and `batchedUpdates`. The default batch size is effectively all updates within the same call stack. `flushSync` flushes the entire batch queue. React 18's automatic batching also works with native event listeners (`addEventListener`).",[96,182,389,390],"react-18","updates",{"id":392,"category":58,"question":393,"answer":394,"level":363,"tags":395},50,"What is Suspense and how does it work internally? Explain data fetching with Suspense and its limitations.","**Concept Explanation:**\nSuspense is a React component that lets you \"wait\" for some asynchronous operation (like data fetching, code splitting) before rendering. Internally, it works by catching promises thrown during rendering. When a promise is thrown, React suspends rendering, finds the nearest Suspense boundary, and renders the fallback. Once the promise resolves, React retries rendering.\n\n**Internal Mechanism:**\n- Components can \"throw\" a promise (or use `use` hook in React 19).\n- React catches it and marks the component as suspended.\n- Suspense boundary displays fallback.\n- After promise resolves, React re-renders the component subtree.\n\n**Code Example:**\n```jsx\nimport { Suspense, useState } from 'react';\n\n\u002F\u002F Resource (simplified)\nfunction createResource(promise) {\n  let status = 'pending';\n  let result;\n  let suspender = promise.then(\n    (r) => { status = 'success'; result = r; },\n    (e) => { status = 'error'; result = e; }\n  );\n  return {\n    read() {\n      if (status === 'pending') throw suspender;\n      if (status === 'error') throw result;\n      return result;\n    }\n  };\n}\n\nconst resource = createResource(fetchData());\n\nfunction DataComponent() {\n  const data = resource.read(); \u002F\u002F may throw promise\n  return \u003Cdiv>{data}\u003C\u002Fdiv>;\n}\n\nfunction App() {\n  return (\n    \u003CSuspense fallback={\u003Cdiv>Loading...\u003C\u002Fdiv>}>\n      \u003CDataComponent \u002F>\n    \u003C\u002FSuspense>\n  );\n}\n\n\u002F\u002F Using `use` hook (React 19)\nimport { use, Suspense } from 'react';\n\nfunction DataComponent({ promise }) {\n  const data = use(promise); \u002F\u002F React 19\n  return \u003Cdiv>{data}\u003C\u002Fdiv>;\n}\n```\n\n**Execution Flow:**\n1. Render DataComponent.\n2. Resource.read() throws a promise.\n3. React catches it, suspends, looks for nearest Suspense.\n4. Renders fallback.\n5. When promise resolves, React re-renders DataComponent, now data available.\n\n**Reactivity Explanation:**\nSuspense makes async dependencies part of the rendering lifecycle, enabling declarative loading states.\n\n**Practical Usage:**\n- Code splitting with `React.lazy`.\n- Data fetching with Relay, Next.js, or custom Suspense integration.\n- Loading UI while assets load.\n\n**Common Mistakes:**\n- Using Suspense without a supported data fetching library (won't work out-of-the-box).\n- Throwing promises outside React lifecycle (no Suspense boundary).\n- Not providing fallback.\n\n**Interview Follow-ups:**\n- What is the difference between Suspense for code splitting vs data fetching?\n- Why doesn't React provide a built-in `fetch` Suspense integration?\n- How does Suspense handle errors?\n\n**Best Practices:**\n- Use Suspense with `React.lazy` for route splitting.\n- For data fetching, use libraries that support Suspense (Relay, Next.js App Router).\n- Use error boundaries alongside Suspense for error handling.\n\n**Performance Considerations:**\n- Suspense can prevent waterfalls by triggering loading for nested components.\n- Multiple Suspense boundaries can be nested for granular loading.\n\n**Production Recommendations:**\n- Use frameworks (Next.js, Remix) that implement Suspense for data.\n- For custom solutions, consider `react-suspense-fetch` or similar.\n\n**Node.js \u002F SSR Behavior:**\nSuspense on server can be used with streaming SSR (render fallback, then stream resolved content).\n\n**Latest React Patterns:**\n- React 19 `use` hook integrates with Suspense.\n- Suspense for Server Components in Next.js App Router.\n\n**TypeScript Example:**\n```tsx\ninterface Resource\u003CT> {\n  read: () => T;\n}\n```\n\n**Interview Tip:**\nExplain that Suspense is a mechanism, not a data-fetching library. It works with any async operation that can throw a promise.\n\n**Common Follow-up:**\n\"Does Suspense replace loading state management?\" (It provides declarative loading, but you still need error boundaries)\n\n**Real-world Example:**\nA profile page with user info and posts. With Suspense, you can start fetching both in parallel, show skeleton, and render each as data arrives.\n\n**Advanced Notes:**\nReact's `use` hook (experimental) simplifies promise consumption. Suspense also works with `startTransition` to avoid showing fallback for pending data (avoid flash of loading). The next version of Suspense for data fetching is expected to work with cached resources and concurrent features.",[262,113,396,397],"async","concurrent",{"id":399,"category":400,"question":401,"answer":402,"level":363,"tags":403},51,"SSR & Hydration","Explain Streaming SSR and Selective Hydration. How do they improve performance in React 18?","**Concept Explanation:**\nStreaming SSR allows the server to send HTML in chunks as components resolve asynchronously, rather than waiting for the whole page. Selective Hydration lets the browser start hydrating components as they become interactive, without waiting for the entire HTML to load. Together, they improve Time To First Byte (TTFB) and Time To Interactive (TTI).\n\n**How Streaming SSR Works:**\n- Server uses `renderToPipeableStream` (Node) or `renderToReadableStream` (Edge).\n- It renders the shell (synchronous parts) first, then streams additional content as Suspense boundaries resolve.\n- Client progressively receives and displays content.\n\n**Selective Hydration:**\n- Hydration begins immediately for the shell.\n- Components are hydrated in order of user interaction (click on a component triggers its hydration).\n- Low-priority components can be hydrated later, even after initial paint.\n\n**Code Example:**\n```jsx\n\u002F\u002F Server (Node.js)\nimport { renderToPipeableStream } from 'react-dom\u002Fserver';\n\napp.get('\u002F', (req, res) => {\n  const { pipe } = renderToPipeableStream(\u003CApp \u002F>, {\n    bootstrapScripts: ['\u002Fmain.js'],\n    onShellReady() {\n      res.setHeader('content-type', 'text\u002Fhtml');\n      pipe(res);\n    },\n  });\n});\n\n\u002F\u002F Component with Suspense\nimport { Suspense, lazy } from 'react';\nconst Comments = lazy(() => import('.\u002FComments'));\n\nfunction App() {\n  return (\n    \u003Cdiv>\n      \u003Ch1>Post\u003C\u002Fh1>\n      \u003CSuspense fallback={\u003Cdiv>Loading comments...\u003C\u002Fdiv>}>\n        \u003CComments \u002F>\n      \u003C\u002FSuspense>\n    \u003C\u002Fdiv>\n  );\n}\n\u002F\u002F Server streams HTML: first sends shell (h1 and fallback), then later sends comments HTML\n```\n\n**Execution Flow:**\n1. Server starts rendering, sends initial shell (non-async parts).\n2. Client receives shell, displays it, starts hydrating.\n3. Async components resolve on server → stream additional HTML chunks.\n4. Client inserts chunks and hydrates them.\n5. User clicks on a yet-unhydrated component → React prioritizes its hydration.\n\n**Reactivity Explanation:**\nSelective hydration makes the page interactive faster, even if large parts are still loading.\n\n**Practical Usage:**\n- Next.js 14+ App Router uses streaming SSR.\n- Large dashboards with slow data queries.\n\n**Common Mistakes:**\n- Not marking components with Suspense boundaries (everything becomes serial).\n- Putting non-Suspense components after a Suspense boundary delays shell.\n\n**Interview Follow-ups:**\n- How does selective hydration know which components to prioritize?\n- What is the difference between `renderToString` and `renderToPipeableStream`?\n- Can you use streaming SSR without Suspense?\n\n**Best Practices:**\n- Wrap slow data-fetching components in Suspense boundaries.\n- Ensure the shell (above the fold) is fast and not suspended.\n- Use `lazy` for code splitting combined with Suspense.\n\n**Performance Considerations:**\n- Streaming reduces TTFB but may increase total bandwidth.\n- Selective hydration avoids blocking main thread.\n\n**Production Recommendations:**\n- Use frameworks that support streaming SSR (Next.js, Hydrogen).\n- Profile hydration with React DevTools.\n\n**Node.js \u002F SSR Behavior:**\nStreaming requires Node.js `stream` API or Web Streams.\n\n**Latest React Patterns:**\n- React 18 `renderToPipeableStream`.\n- React 19 may further improve selective hydration.\n\n**TypeScript Example:**\n```tsx\nimport { renderToPipeableStream } from 'react-dom\u002Fserver';\n\nconst stream = renderToPipeableStream(\u003CApp \u002F>, {\n  onShellReady() { \u002F* pipe *\u002F },\n});\n```\n\n**Interview Tip:**\nExplain that traditional SSR sends full HTML at once, causing delays for slow data. Streaming sends content as soon as ready.\n\n**Common Follow-up:**\n\"What is the difference between hydration and selective hydration?\" (Hydration is all-or-nothing; selective hydrates in priority order)\n\n**Real-world Example:**\nAn e-commerce product page: product info streams first, then user reviews (slower query), then recommendations. The user can add to cart before reviews load.\n\n**Advanced Notes:**\nSelective hydration listens to clicks and other events to prioritize hydrating the target component. `renderToPipeableStream` also supports `onAllReady` for crawlers. Suspense also works with `startTransition` on client to avoid showing fallback for cached data.",[404,405,406,407],"ssr","streaming","hydration","selective-hydration",{"id":409,"category":360,"question":410,"answer":411,"level":363,"tags":412},52,"How does React handle events internally? Explain the event delegation system and synthetic events.","**Concept Explanation:**\nReact implements a synthetic event system that wraps native browser events for cross-browser consistency. Instead of attaching event handlers to individual DOM nodes, React attaches a single listener per event type at the root container (event delegation). It then dispatches events to the correct components based on the fiber tree. This improves memory efficiency and allows React to manage event priorities.\n\n**How It Works:**\n- When you write `onClick={handler}`, React stores the handler in the fiber node (not directly on DOM).\n- React attaches one listener per event type (e.g., 'click') to the root container.\n- When a native event occurs, React creates a `SyntheticEvent` wrapper.\n- React determines which component(s) to call by traversing the fiber tree using the `target` and propagation.\n\n**Event Flow:**\n1. Native event fires on DOM element.\n2. Event bubbles to root container listener.\n3. React maps the target DOM node to the fiber node.\n4. React builds a list of fiber nodes (from target up to root) that have handlers.\n5. React dispatches synthetic events through the fiber list, respecting `stopPropagation`.\n\n**Code Example (Conceptual):**\n```jsx\n\u002F\u002F Simplified internal mapping\nconst eventHandlers = new Map();\n\n\u002F\u002F React attaches one listener\nroot.addEventListener('click', (nativeEvent) => {\n  const targetFiber = getFiberFromDOM(nativeEvent.target);\n  const syntheticEvent = createSyntheticEvent(nativeEvent);\n  let fiber = targetFiber;\n  do {\n    const handler = fiber.memoizedProps?.onClick;\n    if (handler) {\n      handler(syntheticEvent);\n      if (syntheticEvent.isPropagationStopped()) break;\n    }\n    fiber = fiber.return;\n  } while (fiber);\n});\n```\n\n**Execution Flow:**\n1. User clicks button.\n2. Native click event bubbles to root container.\n3. React's listener catches it, creates `SyntheticBaseEvent`.\n4. React traverses fiber tree, calls `onClick` handlers.\n5. If handler calls `e.preventDefault()`, React calls `nativeEvent.preventDefault()`.\n\n**Reactivity Explanation:**\nThis system allows React to prioritize events (e.g., `onClick` higher than `onScroll`) and to replay events after hydration.\n\n**Practical Usage:**\n- Developers use `onClick`, `onChange` as usual; internal details hidden.\n- Synthetic events work across all browsers identically.\n\n**Common Mistakes:**\n- Expecting native properties like `nativeEvent` to be always available (they are, but synthetic event is pooled historically? No pool in React 17+).\n- Using `e.persist()` (no longer needed in React 17+).\n\n**Interview Follow-ups:**\n- Why does React use event delegation?\n- What are synthetic events and why were they introduced?\n- How does React handle `e.stopPropagation()` with multiple roots?\n\n**Best Practices:**\n- Use native events only when necessary (e.g., `addEventListener` for global listeners).\n- For performance, prefer React synthetic events over manual listeners.\n\n**Performance Considerations:**\n- Single event listener per type reduces memory.\n- Creating synthetic events is cheap but adds some overhead.\n\n**Production Recommendations:**\n- For third-party DOM integration, use `ref` and native event listeners, but cleanup.\n- React 18 prioritizes events based on user interaction.\n\n**Node.js \u002F SSR Behavior:**\nNo events on server; synthetic events are client-only.\n\n**Latest React Patterns:**\n- React 17 changed event delegation to attach to root container (not `document`).\n- React 18's `useTransition` can be triggered from events.\n\n**TypeScript Example:**\n```tsx\nconst handleClick = (e: React.MouseEvent\u003CHTMLButtonElement>) => {\n  e.preventDefault();\n};\n```\n\n**Interview Tip:**\nExplain that synthetic events provide cross-browser consistency and enable React's priority system. The delegation reduces memory footprint.\n\n**Common Follow-up:**\n\"Does React use event pooling?\" (No, since React 17 synthetic events are not pooled)\n\n**Real-world Example:**\nA large list with many interactive items. Without delegation, hundreds of event listeners would be attached; React attaches just one.\n\n**Advanced Notes:**\nReact also has a separate `SyntheticKeyboardEvent`, `SyntheticFocusEvent` etc. The listener map is stored in the `listenerBank`. React supports `onCapture` variants (capture phase). Event plugins (like `SimpleEventPlugin`) process native events. The `ReactDOM` package is responsible for event system.",[54,413,366],"event-delegation",{"id":415,"category":360,"question":416,"answer":417,"level":363,"tags":418},53,"How does the React Compiler (formerly Forget) work? What problems does it solve and how does it differ from manual memoization?","**Concept Explanation:**\nReact Compiler is an experimental build-time tool that automatically memoizes components, eliminating the need for manual `useMemo`, `useCallback`, and `React.memo`. It analyzes JavaScript code, understands React's rules (components must be pure, hooks order stable), and inserts memoization code automatically to prevent unnecessary re-renders.\n\n**How It Works:**\n- Compiler parses the code to an AST.\n- It identifies which values can change and which dependencies are needed.\n- It tracks where props, state, and context are used.\n- It automatically wraps components and hooks with memoization.\n- It uses a concept of \"memoization keys\" based on variable references.\n\n**Code Example:**\n```jsx\n\u002F\u002F Before compilation (manual memoization)\nimport { useMemo, useCallback, memo } from 'react';\n\nconst List = memo(({ items, onSelect }) => {\n  const sorted = useMemo(() => items.sort(), [items]);\n  const handleSelect = useCallback((id) => onSelect(id), [onSelect]);\n  return sorted.map(item => \u003Cdiv onClick={() => handleSelect(item.id)}>{item.name}\u003C\u002Fdiv>);\n});\n\n\u002F\u002F After compilation (automatic)\nconst List = ({ items, onSelect }) => {\n  const sorted = items.sort(); \u002F\u002F compiler memoizes automatically\n  const handleSelect = (id) => onSelect(id);\n  return sorted.map(item => \u003Cdiv onClick={() => handleSelect(item.id)}>{item.name}\u003C\u002Fdiv>);\n};\n\u002F\u002F Compiler adds memoization for sorted and handleSelect, and wraps component with memo\n```\n\n**Execution Flow:**\n- Developer writes plain React code (following rules of React).\n- React Compiler runs as part of build step (e.g., Babel plugin).\n- It outputs transformed code with memoization primitives.\n- At runtime, memoization works just like manual hooks.\n\n**Reactivity Explanation:**\nThe compiler preserves reactivity because it understands dependencies; it only memoizes when beneficial.\n\n**Practical Usage:**\n- Simplify component code by removing manual memoization.\n- Reduce bugs caused by missing dependencies or incorrect memoization.\n- Improve performance by default.\n\n**Common Mistakes:**\n- Breaking React's rules (e.g., mutating state, conditional hooks) may confuse compiler.\n- Relying on compiler without testing.\n\n**Interview Follow-ups:**\n- What are the rules of React that the compiler depends on?\n- Can the compiler optimize all cases?\n- How does it compare to SolidJS or Svelte?\n\n**Best Practices:**\n- Write components pure and follow hooks rules.\n- Use compiler as an optimization, not to fix broken code.\n- Keep using React DevTools to verify memoization.\n\n**Performance Considerations:**\n- Compiler reduces bundle size? (adds some overhead for memoization, but removes manual code).\n- Should be faster than manual memoization because it avoids over-memoizing.\n\n**Production Recommendations:**\n- Experimental; not for production yet.\n- Expected to be available in React 19 or later.\n\n**Node.js \u002F SSR Behavior:**\nCompiler works on both client and server builds.\n\n**Latest React Patterns:**\n- React 19 may include React Compiler as an optional feature.\n- Use with `react-forget` Babel plugin (early version).\n\n**TypeScript Example:**\n(Compiler works with TypeScript via ts-patch)\n\n**Interview Tip:**\nExplain that the React Compiler aims to make manual memoization obsolete, reducing boilerplate and potential errors.\n\n**Common Follow-up:**\n\"Will React Compiler make `useMemo` and `useCallback` obsolete?\" (Probably for most cases, but may still be needed for complex custom hooks)\n\n**Real-world Example:**\nA large component tree with deeply nested components. Without memoization, every parent re-render causes child re-renders. Manual memoization is tedious. Compiler does it automatically.\n\n**Advanced Notes:**\nThe compiler uses a technique called \"memoization of reactive scopes.\" It analyzes variable liveness and inserts `useMemo` only when necessary. It also handles `useCallback` for functions passed as props. The compiler does not replace `useMemo` for expensive computations (compiler can detect those). The project was internally named \"React Forget\"; at Meta, it reduced re-renders significantly.",[419,225,196,420],"react-compiler","optimization",{"id":422,"category":400,"question":423,"answer":424,"level":363,"tags":425},54,"Explain hydration mismatches in React. What causes them and how can they be fixed?","**Concept Explanation:**\nHydration mismatch occurs when the HTML generated by server-side rendering (SSR) does not match the first render of React on the client. React expects the client DOM to exactly match the server-rendered HTML; otherwise, it will discard the server HTML and re-render on client, causing performance issues and potential UI flickers.\n\n**Common Causes:**\n- Using browser-only APIs (`window`, `localStorage`) during render on server vs client.\n- Random values (e.g., `Math.random()`, `Date.now()`) rendered on server differ.\n- Different data on server vs client (e.g., user authentication state).\n- Incorrect HTML structure (e.g., missing `\u003Ctbody>` in tables).\n\n**Code Example:**\n```jsx\n\u002F\u002F ❌ Causes mismatch\nfunction Component() {\n  const timestamp = Date.now(); \u002F\u002F different on server and client\n  return \u003Cdiv>{timestamp}\u003C\u002Fdiv>;\n}\n\n\u002F\u002F ❌ Using window during render\nfunction Component() {\n  const width = window.innerWidth; \u002F\u002F window undefined on server\n  return \u003Cdiv>{width}\u003C\u002Fdiv>;\n}\n\n\u002F\u002F ✅ Fix: useEffect to run on client only\nfunction Component() {\n  const [timestamp, setTimestamp] = useState(null);\n  useEffect(() => setTimestamp(Date.now()), []);\n  return \u003Cdiv>{timestamp}\u003C\u002Fdiv>;\n}\n\n\u002F\u002F ✅ Alternative: suppressHydrationWarning (use sparingly)\n\u003Cdiv suppressHydrationWarning>{maybeRandom}\u003C\u002Fdiv>\n\n\u002F\u002F ✅ For data: ensure server and client fetch same data\n```\n\n**Execution Flow:**\n1. Server renders HTML, sends to client.\n2. React loads on client, attempts to hydrate.\n3. React compares server-rendered DOM with client's first render.\n4. If mismatches found, React logs warnings and discards server DOM, re-renders from scratch.\n\n**Reactivity Explanation:**\nHydration is the process of attaching event handlers to server-rendered HTML. Mismatches break this process.\n\n**Practical Usage:**\n- Building Next.js or Remix apps with SSR.\n- Using third-party libraries that manipulate DOM.\n\n**Common Mistakes:**\n- Using `useLayoutEffect` on server (causes mismatch).\n- Generating random IDs without stable ID generation (`useId`).\n- Not using `useEffect` for client-only values.\n\n**Interview Follow-ups:**\n- What is the `suppressHydrationWarning` prop and why is it dangerous?\n- How does `useId` help prevent hydration mismatches?\n- How do frameworks like Next.js handle data mismatches?\n\n**Best Practices:**\n- Avoid browser globals during render; use `useEffect`.\n- Use `useId` for generating unique IDs across server\u002Fclient.\n- For random values, either suppress warning (if acceptable) or defer to client.\n- Ensure data fetching is deterministic between server and client.\n\n**Performance Considerations:**\n- Hydration mismatches force full client re-render, negating SSR performance benefits.\n- Use React DevTools to check for hydration warnings.\n\n**Production Recommendations:**\n- Run tests to catch hydration mismatches.\n- Use Next.js `useEffect` or `useState` with `useEffect` for client-only render.\n- For static content, use `suppressHydrationWarning` only as last resort.\n\n**Node.js \u002F SSR Behavior:**\nMismatches are detected during hydration on client; server logs no errors.\n\n**Latest React Patterns:**\n- `useId` (React 18) provides stable IDs across server\u002Fclient.\n- React 19 may introduce better hydration recovery.\n\n**TypeScript Example:**\n```tsx\nimport { useId, useState, useEffect } from 'react';\n\nfunction IdExample() {\n  const id = useId(); \u002F\u002F stable, no mismatch\n  return \u003Cdiv id={id}>Content\u003C\u002Fdiv>;\n}\n```\n\n**Interview Tip:**\nExplain that hydration mismatches are a major pitfall of SSR. Always ensure deterministic rendering between server and client.\n\n**Common Follow-up:**\n\"What is the difference between hydration and reconciliation?\" (Hydration is initial attach; reconciliation is subsequent updates)\n\n**Real-world Example:**\nA component that displays current year in footer. Using `new Date().getFullYear()` renders 2025 on server, but 2026 after client midnight? Mismatch on New Year's Day. Fix: use `useEffect` or suppress.\n\n**Advanced Notes:**\nReact also supports streaming SSR and selective hydration, but mismatches still break the process. The `hydrateRoot` API in React 18 replaced `hydrate`. `createRoot` with `hydrate` option. For data mismatches, frameworks like Next.js use `useEffect` to re-fetch or `useSyncExternalStore`.",[406,404,426,427],"mismatch","react-dom",{"id":429,"category":350,"question":430,"answer":431,"level":363,"tags":432},55,"What are React Server Components (RSC) and how do they differ from client components? Explain the benefits and trade-offs.","**Concept Explanation:**\nReact Server Components are a new paradigm that allows components to run exclusively on the server, with zero JavaScript sent to the client. They can access backend resources (databases, files) directly. Client Components are traditional React components that run in the browser. RSC reduces bundle size, improves initial page load, and enables server-side data fetching without exposing secrets.\n\n**How RSC Works:**\n- Server Components are executed on the server and produce a serializable JSON-like format (not HTML).\n- The output is sent to the client, where it is merged with Client Components.\n- Server Components never re-render on the client; they are static after first send.\n- Client Components can be interleaved within Server Components.\n\n**Code Example:**\n```jsx\n\u002F\u002F Note: This is a Server Component (no 'use client' directive)\nimport { db } from 'server-only';\n\nasync function ProductList() {\n  const products = await db.product.findMany(); \u002F\u002F direct database access\n  return (\n    \u003Cdiv>\n      {products.map(p => (\n        \u003Cdiv key={p.id}>{p.name}\u003C\u002Fdiv>\n      ))}\n    \u003C\u002Fdiv>\n  );\n}\n\n\u002F\u002F Client Component ('use client' directive)\n'use client';\nimport { useState } from 'react';\n\nfunction Counter() {\n  const [count, setCount] = useState(0);\n  return \u003Cbutton onClick={() => setCount(count+1)}>{count}\u003C\u002Fbutton>;\n}\n\n\u002F\u002F App component (Server Component by default)\nimport ProductList from '.\u002FProductList';\nimport Counter from '.\u002FCounter';\n\nexport default function Page() {\n  return (\n    \u003Cdiv>\n      \u003Ch1>Products\u003C\u002Fh1>\n      \u003CProductList \u002F> {\u002F* server rendered *\u002F}\n      \u003CCounter \u002F>      {\u002F* client component *\u002F}\n    \u003C\u002Fdiv>\n  );\n}\n```\n\n**Execution Flow:**\n1. Server receives request.\n2. It renders Server Component tree, fetching data, resolving dependencies.\n3. Server serializes the output (React elements) into a special format.\n4. Client receives stream, reconstructs the tree, and hydrates Client Components.\n5. Client Components become interactive; Server Components are never re-fetched.\n\n**Reactivity Explanation:**\nServer Components have no reactivity on client; they are static. Client Components work as usual. RSCs can re-fetch via navigation (like Next.js App Router).\n\n**Practical Usage:**\n- Data fetching with direct database access (no API layer).\n- Large static parts of UI (product catalogs, blog posts).\n- Reducing client bundle size.\n\n**Common Mistakes:**\n- Trying to use hooks (useState, useEffect) in Server Components (not allowed).\n- Putting 'use client' on every component (defeats purpose).\n- Assuming Server Components can handle user interactions (they can't).\n\n**Interview Follow-ups:**\n- How do Server Components communicate with Client Components?\n- What is the 'use client' directive?\n- Can Server Components be used without a framework?\n\n**Best Practices:**\n- Default to Server Components; add 'use client' when needed (state, effects, browser APIs).\n- Pass serializable props from Server to Client components.\n- Use Suspense with Server Components for streaming.\n\n**Performance Considerations:**\n- RSC reduces client bundle size dramatically.\n- Data fetching on server reduces round trips.\n- No hydration for Server Components, improving TTI.\n\n**Production Recommendations:**\n- Use Next.js App Router (stable) or Remix with RSC experimental.\n- Not recommended for custom setups (complexity).\n\n**Node.js \u002F SSR Behavior:**\nRSC is a server-only feature; it extends SSR. It does not replace traditional SSR but complements it.\n\n**Latest React Patterns:**\n- Next.js 13+ App Router uses RSC by default.\n- React 19 will have stable RSC release.\n\n**TypeScript Example:**\n```tsx\nexport default async function Page({ params }: { params: { id: string } }) {\n  const data = await fetchData(params.id);\n  return \u003Cdiv>{data}\u003C\u002Fdiv>;\n}\n```\n\n**Interview Tip:**\nExplain that RSC solves the problem of large client bundles and the need for API layers. They are a shift in React's architecture.\n\n**Common Follow-up:**\n\"Can Server Components replace SSR?\" (No, they serve different purposes; RSC is about component model, SSR about initial HTML)\n\n**Real-world Example:**\nAn e-commerce site: product listing (Server Component) fetches from DB directly; add-to-cart button (Client Component) manages state. No API needed for product data.\n\n**Advanced Notes:**\nRSC uses a new format called \"React Flight\" for serialization. Server Components cannot import Client Components that depend on server-only modules. They support async\u002Fawait natively. In Next.js, `'use client'` marks the boundary. RSC also enables zero-bundle-size components.",[433,434,435,354],"server-components","rsc","nextjs",{"id":437,"category":175,"question":438,"answer":439,"level":363,"tags":440},56,"How do you optimize large lists in React? Discuss virtualization, windowing, and techniques like react-window.","**Concept Explanation:**\nRendering large lists with thousands of items can cause performance issues because React must create and update many DOM nodes. Windowing (virtualization) is the technique of rendering only the items currently visible in the viewport, plus a small buffer. This reduces DOM nodes, memory usage, and initial render time. Libraries like `react-window` and `react-virtualized` implement this efficiently.\n\n**How Virtualization Works:**\n- Calculate which items are visible based on scroll position and item heights.\n- Only render those items in the DOM.\n- Use absolute positioning or transform to create scroll bar with full list height.\n- When user scrolls, unmount out-of-view items and mount new ones.\n\n**Code Example:**\n```jsx\nimport { FixedSizeList as List } from 'react-window';\n\nconst Row = ({ index, style }) => (\n  \u003Cdiv style={style}>Row {index}\u003C\u002Fdiv>\n);\n\nfunction VirtualizedList({ items }) {\n  return (\n    \u003CList\n      height={400}\n      itemCount={items.length}\n      itemSize={35}\n      width={300}\n    >\n      {Row}\n    \u003C\u002FList>\n  );\n}\n\n\u002F\u002F Variable height rows\nimport { VariableSizeList } from 'react-window';\n\nconst VariableRow = ({ index, style }) => (\n  \u003Cdiv style={style}>Row {index} - height varies\u003C\u002Fdiv>\n);\n\nfunction VariableList({ items }) {\n  const getItemSize = (index) => items[index].height;\n  return (\n    \u003CVariableSizeList\n      height={400}\n      itemCount={items.length}\n      itemSize={getItemSize}\n      width={300}\n    >\n      {VariableRow}\n    \u003C\u002FVariableSizeList>\n  );\n}\n\n\u002F\u002F With React Query for infinite scroll\nimport { useInfiniteQuery } from '@tanstack\u002Freact-query';\nimport { FixedSizeList } from 'react-window';\nimport InfiniteLoader from 'react-window-infinite-loader';\n\nfunction InfiniteList() {\n  const { data, fetchNextPage, hasNextPage } = useInfiniteQuery({\n    queryKey: ['items'],\n    queryFn: fetchPage,\n    getNextPageParam: (lastPage) => lastPage.nextCursor,\n  });\n  const items = data?.pages.flatMap(p => p.items) || [];\n\n  const loadMoreItems = () => hasNextPage && fetchNextPage();\n  const isItemLoaded = (index) => index \u003C items.length;\n\n  return (\n    \u003CInfiniteLoader\n      isItemLoaded={isItemLoaded}\n      itemCount={items.length + 1}\n      loadMoreItems={loadMoreItems}\n    >\n      {({ onItemsRendered, ref }) => (\n        \u003CFixedSizeList\n          height={400}\n          itemCount={items.length + 1}\n          itemSize={50}\n          onItemsRendered={onItemsRendered}\n          ref={ref}\n        >\n          {({ index, style }) => (\n            \u003Cdiv style={style}>\n              {isItemLoaded(index) ? items[index].name : 'Loading...'}\n            \u003C\u002Fdiv>\n          )}\n        \u003C\u002FFixedSizeList>\n      )}\n    \u003C\u002FInfiniteLoader>\n  );\n}\n```\n\n**Execution Flow:**\n1. List component calculates viewport start\u002Fend indices.\n2. Renders only those items, with empty space above\u002Fbelow.\n3. On scroll, recalculates indices and re-renders.\n4. Unmounted items are removed, new items added.\n\n**Reactivity Explanation:**\nChanges to item data cause re-renders, but only for visible items.\n\n**Practical Usage:**\n- Infinite scroll feeds (Twitter, Instagram).\n- Data grids with thousands of rows.\n- Large dropdowns with many options.\n\n**Common Mistakes:**\n- Not using `React.memo` on row components (each scroll re-renders all rows).\n- Putting heavy components inside rows without memoization.\n- Using virtualization for small lists (overhead).\n\n**Interview Follow-ups:**\n- How does `react-window` differ from `react-virtualized`?\n- What is the significance of `itemSize` in fixed-size lists?\n- How do you handle dynamic row heights?\n\n**Best Practices:**\n- Memoize row components with `React.memo`.\n- Use `overscanCount` to render extra rows for smooth scrolling.\n- For infinite scroll, use `InfiniteLoader` or similar.\n\n**Performance Considerations:**\n- Virtualization reduces DOM nodes from thousands to ~20, massive performance gain.\n- Scrolling triggers re-renders; keep row components lightweight.\n\n**Production Recommendations:**\n- Use `react-window` for fixed or variable heights.\n- For complex tables, consider `react-virtualized` or `react-data-grid`.\n- Use `useDebounce` for scroll events if needed.\n\n**Node.js \u002F SSR Behavior:**\nVirtualized lists are not suitable for SSR (height calculations require client). Usually render static list on server, then hydrate.\n\n**Latest React Patterns:**\n- React 19's `use` and `Suspense` can work with virtualization.\n- `react-window` with `useTransition` to prioritize list updates.\n\n**TypeScript Example:**\n```tsx\nconst Row: React.FC\u003C{ index: number; style: React.CSSProperties }> = ({ index, style }) => (\n  \u003Cdiv style={style}>Row {index}\u003C\u002Fdiv>\n);\n```\n\n**Interview Tip:**\nExplain that rendering 10,000 DOM nodes is expensive; virtualization keeps only what's visible, making large lists feasible.\n\n**Common Follow-up:**\n\"What is the difference between virtualization and pagination?\" (Virtualization keeps all data but renders only visible; pagination fetches subsets)\n\n**Real-world Example:**\nA spreadsheet-like table with 100,000 rows. Without virtualization, the browser would freeze; with virtualization, it's performant.\n\n**Advanced Notes:**\nReact Window uses a dynamic `style` prop with `position: absolute` and `top`. It also supports grid virtualization (`FixedSizeGrid`). For tables with varying column widths, consider `react-virtualized` (more features). CSS `content-visibility: auto` can help but not as efficient as dedicated virtualization.",[441,442,69,182],"virtualization","windowing",{"id":444,"category":445,"question":446,"answer":447,"level":363,"tags":448},57,"Security","What are common security vulnerabilities in React applications and how do you mitigate them? (XSS, CSRF, prototype pollution)","**Concept Explanation:**\nReact provides built-in protection against XSS (Cross-site Scripting) by escaping content in JSX. However, vulnerabilities can still occur when using `dangerouslySetInnerHTML`, user-controlled URLs, or server-side rendering without proper sanitization. CSRF (Cross-site Request Forgery) requires token-based protection. Prototype pollution can happen via unsafe object merges or JSON parsing.\n\n**XSS Mitigation:**\n```jsx\n\u002F\u002F Safe – React escapes by default\nconst userInput = '\u003Cimg src=x onerror=alert(1)>';\nreturn \u003Cdiv>{userInput}\u003C\u002Fdiv>; \u002F\u002F renders as text, not HTML\n\n\u002F\u002F Unsafe – using dangerouslySetInnerHTML\n\u003Cdiv dangerouslySetInnerHTML={{ __html: userInput }} \u002F> \u002F\u002F XSS risk\n\n\u002F\u002F Mitigation: sanitize HTML with DOMPurify\nimport DOMPurify from 'dompurify';\nconst sanitized = DOMPurify.sanitize(userInput);\n\u003Cdiv dangerouslySetInnerHTML={{ __html: sanitized }} \u002F>\n\n\u002F\u002F Unsafe – href with javascript:\n\u003Ca href={userInput}>Link\u003C\u002Fa> \u002F\u002F if userInput = \"javascript:alert(1)\"\n\u002F\u002F Mitigation: validate URL scheme\nfunction isValidUrl(url) {\n  const allowed = ['http:', 'https:', 'mailto:'];\n  try {\n    const parsed = new URL(url);\n    return allowed.includes(parsed.protocol);\n  } catch { return false; }\n}\n```\n\n**CSRF Mitigation:**\n```jsx\n\u002F\u002F Use CSRF tokens (backend sets cookie, frontend sends header)\nconst csrfToken = document.querySelector('meta[name=\"csrf-token\"]').content;\nfetch('\u002Fapi\u002Fdata', {\n  method: 'POST',\n  headers: { 'X-CSRF-Token': csrfToken },\n});\n\u002F\u002F Set SameSite cookie attribute\n\u002F\u002F In Express: res.cookie('session', token, { sameSite: 'strict', secure: true })\n```\n\n**Prototype Pollution:**\n```jsx\n\u002F\u002F Unsafe merge\nfunction merge(target, source) {\n  Object.assign(target, source); \u002F\u002F if source has __proto__, pollutes\n}\n\n\u002F\u002F Mitigation: avoid merging user-controlled objects\n\u002F\u002F Use Map instead of plain objects for dynamic keys\nconst map = new Map();\n\n\u002F\u002F Or freeze prototype\nObject.freeze(Object.prototype);\n\n\u002F\u002F Use libraries that block prototype pollution (like lodash merge with options)\nimport _ from 'lodash';\n_.mergeWith(target, source, (objValue, srcValue, key) => {\n  if (key === '__proto__') return objValue;\n});\n```\n\n**Code Example (Comprehensive):**\n```jsx\nimport DOMPurify from 'dompurify';\n\nfunction SafeComponent({ userProvidedHtml, userProvidedUrl, userData }) {\n  \u002F\u002F 1. XSS: sanitize HTML\n  const sanitizedHtml = DOMPurify.sanitize(userProvidedHtml);\n\n  \u002F\u002F 2. XSS: validate URL\n  const safeUrl = (() => {\n    try {\n      const url = new URL(userProvidedUrl);\n      return ['http:', 'https:'].includes(url.protocol) ? userProvidedUrl : '#';\n    } catch { return '#'; }\n  })();\n\n  \u002F\u002F 3. Never eval user input\n  \u002F\u002F new Function(userInput) is dangerous\n\n  \u002F\u002F 4. Use Content Security Policy headers (helmet in Express)\n  \u002F\u002F meta tag in HTML\n\n  return (\n    \u003Cdiv>\n      \u003Ca href={safeUrl}>Safe Link\u003C\u002Fa>\n      \u003Cdiv dangerouslySetInnerHTML={{ __html: sanitizedHtml }} \u002F>\n      \u003Cdiv>{userData}\u003C\u002Fdiv> {\u002F* escaped automatically *\u002F}\n    \u003C\u002Fdiv>\n  );\n}\n```\n\n**Practical Usage:**\n- Never trust user input; always sanitize before rendering.\n- Use `helmet` in Express for security headers (CSP, XSS protection).\n- Implement CSRF tokens for state-changing requests.\n\n**Common Mistakes:**\n- Using `innerHTML` or `dangerouslySetInnerHTML` without sanitization.\n- Storing sensitive data in localStorage (accessible via XSS).\n- Not setting `SameSite=Strict` for cookies.\n\n**Interview Follow-ups:**\n- Does React fully protect against XSS? (No, certain patterns bypass escaping)\n- What is Content Security Policy and how does it help?\n- How do you prevent prototype pollution in React apps?\n\n**Best Practices:**\n- Avoid `dangerouslySetInnerHTML` unless absolutely necessary.\n- Use `helmet` for CSP headers.\n- Sanitize URLs with valid protocol checking.\n- Use `Object.freeze(Object.prototype)` early in app.\n\n**Performance Considerations:**\n- Sanitization adds overhead; use sparingly.\n- CSP reports can be sent to monitoring.\n\n**Production Recommendations:**\n- Use a security linter (eslint-plugin-security).\n- Run dependency audits for prototype pollution vulnerabilities.\n- Implement nonce-based CSP for inline scripts.\n\n**Node.js \u002F SSR Behavior:**\nSanitization should happen both on server and client for SSR.\n\n**Latest React Patterns:**\n- React 19 may add more security features.\n- Trusted Types API can prevent DOM XSS.\n\n**TypeScript Example:**\n```tsx\nimport DOMPurify from 'dompurify';\n\nconst sanitized = DOMPurify.sanitize(unsafeString);\n```\n\n**Interview Tip:**\nExplain that React's escaping is effective but not sufficient for all cases. Developers must be aware of the remaining attack surfaces.\n\n**Common Follow-up:**\n\"What is the difference between XSS and CSRF?\" (XSS injects scripts; CSRF forges requests)\n\n**Real-world Example:**\nA comment section that allows formatted text with HTML. Using `dangerouslySetInnerHTML` without sanitization would allow script injection. DOMPurify allows only safe tags.\n\n**Advanced Notes:**\nPrototype pollution is less common in React but can occur in utility libraries. Use `Map` for key-value stores. CSP with `script-src 'self'` blocks inline scripts. React's future may include built-in sanitization.\n\n---\n\n(I will continue with remaining advanced questions, but due to length limit, I will provide the complete set. Please note the answer must be complete JSON. I'll continue generating.)",[449,450,451,452],"security","xss","csrf","prototype-pollution",{"id":454,"category":350,"question":455,"answer":456,"level":363,"tags":457},58,"How do you implement micro-frontends with React? Discuss module federation, shared dependencies, and trade-offs.","**Concept Explanation:**\nMicro-frontends extend microservices to the frontend: multiple independent React applications (remotes) composed into a single shell (host). Webpack 5's Module Federation allows sharing dependencies, remote loading of components at runtime, and independent deployment. Trade-offs include increased complexity, bundle duplication (or shared via singleton), and cross-team coordination.\n\n**How Module Federation Works:**\n- Each remote app exposes specific components\u002Fmodules.\n- Host app imports remotes dynamically at runtime.\n- Dependencies (like React) can be shared as singletons to avoid duplication.\n- Webpack generates remote entry files with manifests.\n\n**Code Example:**\n```jsx\n\u002F\u002F webpack.config.js (host)\nnew ModuleFederationPlugin({\n  name: 'host',\n  remotes: {\n    checkout: 'checkout@http:\u002F\u002Flocalhost:3001\u002FremoteEntry.js',\n    products: 'products@http:\u002F\u002Flocalhost:3002\u002FremoteEntry.js',\n  },\n  shared: { react: { singleton: true, eager: true }, 'react-dom': { singleton: true } },\n});\n\n\u002F\u002F Host App.jsx\nimport React, { Suspense, lazy } from 'react';\n\nconst RemoteCheckout = lazy(() => import('checkout\u002FCheckout'));\nconst RemoteProducts = lazy(() => import('products\u002FProductList'));\n\nfunction App() {\n  return (\n    \u003Cdiv>\n      \u003CSuspense fallback={\u003Cdiv>Loading Products...\u003C\u002Fdiv>}>\n        \u003CRemoteProducts \u002F>\n      \u003C\u002FSuspense>\n      \u003CSuspense fallback={\u003Cdiv>Loading Checkout...\u003C\u002Fdiv>}>\n        \u003CRemoteCheckout \u002F>\n      \u003C\u002FSuspense>\n    \u003C\u002Fdiv>\n  );\n}\n\n\u002F\u002F Remote app webpack.config.js\nexport default {\n  plugins: [\n    new ModuleFederationPlugin({\n      name: 'products',\n      filename: 'remoteEntry.js',\n      exposes: {\n        '.\u002FProductList': '.\u002Fsrc\u002FProductList',\n      },\n      shared: { react: { singleton: true }, 'react-dom': { singleton: true } },\n    }),\n  ],\n};\n```\n\n**Execution Flow:**\n1. Host loads main bundle.\n2. When `RemoteCheckout` is rendered, host fetches `remoteEntry.js` from checkout server.\n3. Webpack runtime resolves the remote module.\n4. Remote modules share React instance if configured as singleton.\n5. Components render normally.\n\n**Reactivity Explanation:**\nRemote components behave like local components; state updates work normally.\n\n**Practical Usage:**\n- Large enterprises with multiple teams owning different sections.\n- Independent deployment of features (like checkout, product catalog).\n- Legacy migration: new React app embedded in old app.\n\n**Common Mistakes:**\n- Not handling version mismatches of shared dependencies.\n- Over-shared dependencies causing conflicts.\n- Not using Suspense for loading remote components.\n\n**Interview Follow-ups:**\n- How does Module Federation differ from iframe-based micro-frontends?\n- What is the role of the `shared` configuration?\n- How do you handle CSS collisions between remotes?\n\n**Best Practices:**\n- Share React and ReactDOM as singletons to reduce bundle size.\n- Use version ranges in shared config for compatibility.\n- Implement error boundaries for remote failures.\n- Use CSS Modules or styled-components for style isolation.\n\n**Performance Considerations:**\n- Remote components are loaded lazily, reducing initial bundle.\n- Shared dependencies avoid duplication but require version alignment.\n- Network overhead for multiple remoteEntry.js files.\n\n**Production Recommendations:**\n- Use Module Federation with webpack 5, or consider frameworks (Bit, Nx).\n- Deploy remotes to CDN with versioned URLs for cache busting.\n- Implement a service discovery mechanism for remotes (API endpoint).\n\n**Node.js \u002F SSR Behavior:**\nModule Federation works with SSR via Node.js runtime federation (complex).\n\n**Latest React Patterns:**\n- React can be used with Module Federation seamlessly.\n- Next.js 13+ supports Module Federation via plugins.\n\n**TypeScript Example:**\n```tsx\ndeclare module 'products\u002FProductList' {\n  const ProductList: React.ComponentType\u003C{}>;\n  export default ProductList;\n}\n```\n\n**Interview Tip:**\nExplain that micro-frontends solve organizational scaling but add runtime complexity. Module Federation is Webpack's answer to dynamic module loading.\n\n**Common Follow-up:**\n\"What is the alternative to Module Federation?\" (Single-spa, iframes, custom runtime integration)\n\n**Real-world Example:**\nAn e-commerce platform with teams: checkout team, product listing team, user account team. Each deploys independently; the shell integrates them.\n\n**Advanced Notes:**\nModule Federation also supports `eager` sharing, `requiredVersion` checks, and fallback modules. It works with any frontend framework, not just React. Remotes can also expose entire applications (not just components). Security: Ensure remoteEntry.js comes from trusted domains.",[458,459,460,354],"micro-frontends","module-federation","webpack",{"id":462,"category":175,"question":463,"answer":464,"level":363,"tags":465},59,"How do you use React DevTools and profiling to identify and fix performance bottlenecks?","**Concept Explanation:**\nReact DevTools provides a Profiler tab to record interactions and measure component render times, commits, and why components re-rendered. You can identify slow components, unnecessary re-renders, and optimization opportunities. The profiler shows flame graphs, ranked charts, and timing details. It also supports interactive debugging by highlighting updates.\n\n**How to Profile:**\n1. Install React DevTools browser extension.\n2. Open DevTools → Components\u002FProfiler tab.\n3. Click record (circle) button.\n4. Interact with your app.\n5. Stop recording.\n6. Analyze results.\n\n**Key Metrics:**\n- **Render duration:** time taken to render component (including children).\n- **Commit duration:** time to apply changes to DOM.\n- **Why did this render?** Click on component to see what prop\u002Fstate changed.\n\n**Code Example (Adding Profiler component):**\n```jsx\nimport { Profiler } from 'react';\n\nfunction onRenderCallback(\n  id, \u002F\u002F the Profiler tree's id\n  phase, \u002F\u002F \"mount\" or \"update\"\n  actualDuration, \u002F\u002F time spent rendering\n  baseDuration, \u002F\u002F estimated time without memoization\n  startTime,\n  commitTime,\n  interactions\n) {\n  console.log(`${id} (${phase}) rendered in ${actualDuration}ms`);\n  \u002F\u002F Send to analytics\n}\n\nfunction App() {\n  return (\n    \u003CProfiler id=\"App\" onRender={onRenderCallback}>\n      \u003CMyComponent \u002F>\n    \u003C\u002FProfiler>\n  );\n}\n```\n\n**Identifying Bottlenecks:**\n- Flame graph: Hover over bars to see render times; wide bars = slow.\n- Ranked chart: Sorted by render duration; top components are candidates for optimization.\n- \"Why did this render?\" info: Shows changed props\u002Fstate.\n\n**Fixes based on Profiler findings:**\n- Unnecessary re-renders → add `React.memo`, use `useCallback`\u002F`useMemo`.\n- Slow render → split component, virtualize large lists, move expensive code to `useMemo`.\n- Large commit phase → reduce DOM operations, batch updates.\n\n**Example Fix:**\n```jsx\n\u002F\u002F Before (slow)\nfunction Parent() {\n  const [count, setCount] = useState(0);\n  const [items, setItems] = useState(longList);\n\n  return (\n    \u003C>\n      \u003Cbutton onClick={() => setCount(c => c+1)}>Count: {count}\u003C\u002Fbutton>\n      \u003CExpensiveList items={items} \u002F> {\u002F* re-renders even if items unchanged *\u002F}\n    \u003C\u002F>\n  );\n}\n\n\u002F\u002F After optimization\nconst MemoizedExpensiveList = React.memo(ExpensiveList);\nfunction Parent() {\n  const [count, setCount] = useState(0);\n  const [items, setItems] = useState(longList);\n\n  \u002F\u002F Buttons with useCallback to stabilize\n  const handleCount = useCallback(() => setCount(c => c+1), []);\n\n  return (\n    \u003C>\n      \u003Cbutton onClick={handleCount}>Count: {count}\u003C\u002Fbutton>\n      \u003CMemoizedExpensiveList items={items} \u002F>\n    \u003C\u002F>\n  );\n}\n```\n\n**Practical Usage:**\n- Regularly profile after major features.\n- Measure before and after optimization.\n- Use profiler in development to catch regressions.\n\n**Common Mistakes:**\n- Profiling with dev build (performance worse than prod).\n- Over-optimizing based on isolated profiler data.\n- Not using the \"why did this render\" feature.\n\n**Interview Follow-ups:**\n- What is the difference between `actualDuration` and `baseDuration`?\n- How do you profile in production?\n- Can you see effects (useEffect) timing in profiler?\n\n**Best Practices:**\n- Use production builds for accurate profiling.\n- Record multiple interactions to find patterns.\n- Combine with browser performance tab (core web vitals).\n\n**Performance Considerations:**\n- Profiler itself adds overhead; don't leave in production.\n- Use `onRender` callback to collect metrics in production (opt-in).\n\n**Production Recommendations:**\n- Use `react-devtools` standalone for mobile debugging.\n- Send profiling data to monitoring tools (Sentry, Datadog).\n- Automate performance regression tests with Lighthouse CI.\n\n**Node.js \u002F SSR Behavior:**\nProfiler works only on client; SSR has no interactive rendering.\n\n**Latest React Patterns:**\n- React 18 profiler supports concurrent rendering.\n- Timeline tab for scheduling visualization.\n\n**TypeScript Example:**\n```tsx\nconst onRender = (id, phase, actualDuration) => {\n  console.log(`${id} ${phase}: ${actualDuration}ms`);\n};\n```\n\n**Interview Tip:**\nExplain that the profiler is essential for data-driven optimization. Always measure before optimizing.\n\n**Common Follow-up:**\n\"What is the purpose of `baseDuration`?\" (Estimated render time assuming memoization; helps identify memoization candidates)\n\n**Real-world Example:**\nA dashboard re-rendered every second due to real-time data. Profiler showed a list component taking 200ms each update. Virtualization and memoization reduced it to 20ms.\n\n**Advanced Notes:**\nReact also offers `why-did-you-render` library as a dev tool. The profiler's flame graph can be exported. `React.Profiler` component can be used to measure specific subtrees. For concurrent rendering, the profiler tracks multiple commits.",[179,181,182,420],{"id":467,"category":360,"question":468,"answer":469,"level":363,"tags":470},60,"How does React handle state updates with hooks? Explain the linked list of hooks and why order matters.","**Concept Explanation:**\nReact stores hooks state in a linked list attached to the component's fiber node. Each hook call (useState, useEffect, etc.) creates a hook object with its state and next pointer. The order of hook calls must be consistent across renders because React relies on the index to retrieve the correct hook state. This is why conditional hooks are forbidden.\n\n**Internal Structure:**\n- Each functional component has a `memoizedState` pointing to the first hook.\n- Each hook node contains `memoizedState` (stored value), `next` pointer, `queue` for updates.\n- During render, React walks the linked list to retrieve hook states.\n\n**Code Example (Simplified conceptual):**\n```jsx\n\u002F\u002F Internal hook object\nconst hook = {\n  memoizedState: null, \u002F\u002F current state\n  baseState: null,\n  baseQueue: null,\n  queue: null, \u002F\u002F update queue\n  next: null, \u002F\u002F next hook\n};\n\n\u002F\u002F Simplified useState implementation\nlet currentlyRenderingFiber = null;\nlet workInProgressHook = null;\n\nfunction useState(initial) {\n  if (currentlyRenderingFiber.alternate === null) {\n    \u002F\u002F mount\n    const hook = {\n      memoizedState: typeof initial === 'function' ? initial() : initial,\n      next: null,\n    };\n    if (workInProgressHook === null) {\n      currentlyRenderingFiber.memoizedState = hook;\n      workInProgressHook = hook;\n    } else {\n      workInProgressHook.next = hook;\n      workInProgressHook = hook;\n    }\n    return [hook.memoizedState, dispatchAction];\n  } else {\n    \u002F\u002F update – use existing hook\n    const hook = workInProgressHook;\n    workInProgressHook = workInProgressHook.next;\n    return [hook.memoizedState, dispatchAction];\n  }\n}\n```\n\n**Why Order Matters:**\n- On first render, hooks are created in sequence.\n- On second render, React expects the same number of hook calls in the same order to find the existing hook nodes.\n- If a hook is skipped (conditional), the next hook will retrieve the previous hook's state (corruption).\n\n**Example of Broken Order:**\n```jsx\nfunction BrokenComponent({ shouldShow }) {\n  const [a, setA] = useState(1);\n  if (shouldShow) {\n    const [b, setB] = useState(2); \u002F\u002F Conditional! \n  }\n  const [c, setC] = useState(3); \u002F\u002F This gets b's state when condition changes\n}\n```\n\n**Execution Flow:**\n1. Component renders.\n2. React initializes `workInProgressHook = fiber.memoizedState`.\n3. Each hook call advances `workInProgressHook` to the next node.\n4. After all hooks, React expects `workInProgressHook` to be null.\n5. If mismatch, React throws an error.\n\n**Reactivity Explanation:**\nThe linked list is how React associates state with each hook call. The order ensures consistency.\n\n**Practical Usage:**\n- Always call hooks at the top level, unconditionally.\n- Use ESLint plugin `eslint-plugin-react-hooks` to enforce rules.\n\n**Common Mistakes:**\n- Calling hooks inside conditions, loops, or nested functions.\n- Early returns before hooks (breaks order).\n\n**Interview Follow-ups:**\n- How does React store state for multiple components?\n- What is the purpose of the `alternate` field?\n- Can you have multiple `useState` with the same initial value? (Yes, order matters)\n\n**Best Practices:**\n- Follow the Rules of Hooks strictly.\n- Use custom hooks to abstract logic, preserving order.\n\n**Performance Considerations:**\n- The linked list traversal is very fast (O(n)).\n- Too many hooks (hundreds) can impact performance, but rare.\n\n**Production Recommendations:**\n- Use `eslint-plugin-react-hooks` to catch order violations.\n- Refactor components with many hooks into smaller components or custom hooks.\n\n**Node.js \u002F SSR Behavior:**\nSame mechanism applies on server (no DOM but state initialization).\n\n**Latest React Patterns:**\n- React 18's `useId`, `useTransition` also rely on order.\n- React 19's `use` hook will follow same order rule.\n\n**TypeScript Example:**\n(Not applicable – internal)\n\n**Interview Tip:**\nExplain that the linked list is the implementation detail behind \"order matters.\" It's like a hidden registry.\n\n**Common Follow-up:**\n\"How does React differentiate between `useState` and `useEffect`?\" (Different fields in hook object, but still ordered)\n\n**Real-world Example:**\nA form component with 20 fields using `useState`. If one field is conditionally rendered (and its useState skipped), subsequent fields get wrong values.\n\n**Advanced Notes:**\nThe hook queue also stores update actions. When an update is triggered, React creates an update node and appends to the queue. During next render, it processes the queue to compute new state. The fiber's `alternate` (work-in-progress) allows React to have two versions of the fiber tree simultaneously.",[47,471,45,366],"linked-list",{"id":473,"category":360,"question":474,"answer":475,"level":363,"tags":476},61,"How does React's `useSyncExternalStore` work and when would you use it?","**Concept Explanation:**\n`useSyncExternalStore` is a React hook for subscribing to external stores (like Redux, Zustand, or browser APIs) in a way that is safe for concurrent rendering. It ensures that tearing (seeing inconsistent state due to concurrent updates) does not occur. It is recommended over manual subscriptions with `useEffect` for external state.\n\n**How It Works:**\n- The hook takes three parameters: `subscribe`, `getSnapshot`, and optional `getServerSnapshot`.\n- React calls `getSnapshot` to read the current store value.\n- React subscribes via `subscribe` and re-renders when the store notifies.\n- During concurrent rendering, React may render multiple times; `getSnapshot` is called each time to get consistent snapshot.\n- If snapshot changes between render and commit, React re-renders to avoid tearing.\n\n**Syntax Explanation:**\n```jsx\nimport { useSyncExternalStore } from 'react';\n\nconst snapshot = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n```\n\n**Code Example:**\n```jsx\n\u002F\u002F External store (e.g., a simple store with listeners)\nlet count = 0;\nconst listeners = new Set();\n\nconst store = {\n  subscribe(listener) {\n    listeners.add(listener);\n    return () => listeners.delete(listener);\n  },\n  getSnapshot() {\n    return count;\n  },\n  increment() {\n    count++;\n    listeners.forEach(listener => listener());\n  },\n};\n\nfunction Counter() {\n  const count = useSyncExternalStore(store.subscribe, store.getSnapshot);\n  return \u003Cbutton onClick={store.increment}>Count: {count}\u003C\u002Fbutton>;\n}\n\n\u002F\u002F Using with Redux (selector)\nimport { useSyncExternalStore } from 'react';\nimport { store } from '.\u002FreduxStore';\n\nfunction useSelector(selector) {\n  return useSyncExternalStore(\n    store.subscribe,\n    () => selector(store.getState()),\n    () => selector(store.getState()) \u002F\u002F server snapshot\n  );\n}\n\n\u002F\u002F Usage\nfunction Profile() {\n  const user = useSelector(state => state.user);\n  return \u003Cdiv>{user.name}\u003C\u002Fdiv>;\n}\n\n\u002F\u002F With window resize (browser API)\nfunction useWindowWidth() {\n  return useSyncExternalStore(\n    (callback) => {\n      window.addEventListener('resize', callback);\n      return () => window.removeEventListener('resize', callback);\n    },\n    () => window.innerWidth,\n    () => 0 \u002F\u002F server fallback\n  );\n}\n```\n\n**Execution Flow:**\n1. Component renders, calls `useSyncExternalStore`.\n2. React calls `getSnapshot` to get store value.\n3. React calls `subscribe` and stores the callback.\n4. When store notifies, React schedules a re-render.\n5. During re-render, React calls `getSnapshot` again; if changed, component updates.\n\n**Reactivity Explanation:**\nThe hook makes the component reactive to external store changes, with concurrency safety.\n\n**Practical Usage:**\n- Integrating Redux or Zustand in React 18+.\n- Subscribing to browser APIs (resize, online, storage).\n- Custom store implementations for concurrent React.\n\n**Common Mistakes:**\n- Not providing `getServerSnapshot` for SSR.\n- Mutating snapshot object incorrectly (should be immutable).\n- Using `useSyncExternalStore` for internal React state (use useState instead).\n\n**Interview Follow-ups:**\n- What problem does `useSyncExternalStore` solve that `useEffect` + subscription doesn't?\n- How does it prevent tearing?\n- When would you not need this hook?\n\n**Best Practices:**\n- Use for external stores not managed by React.\n- Ensure `getSnapshot` returns immutable values (or stable references).\n- Provide server snapshot for SSR.\n\n**Performance Considerations:**\n- `getSnapshot` is called potentially multiple times per render; keep it cheap.\n- Subscribe\u002Funsubscribe functions should be stable (memoized).\n\n**Production Recommendations:**\n- If you're using Redux Toolkit, its hooks already use `useSyncExternalStore` internally.\n- For simple use cases, `useState + useEffect` may suffice if you don't need concurrency.\n\n**Node.js \u002F SSR Behavior:**\nServer snapshot is used during SSR to generate initial content; hydration then uses client snapshot.\n\n**Latest React Patterns:**\n- React 18 introduced this hook; Redux 8+ and Zustand use it.\n- `useSyncExternalStore` is also used by `useTransition` for external stores.\n\n**TypeScript Example:**\n```tsx\nfunction useStore\u003CT>(selector: (state: StoreState) => T): T {\n  return useSyncExternalStore(\n    store.subscribe,\n    () => selector(store.getState()),\n    () => selector(initialStoreState)\n  );\n}\n```\n\n**Interview Tip:**\nExplain that `useSyncExternalStore` is the officially recommended way to subscribe to external stores in React 18+. It solves tearing issues with concurrent rendering.\n\n**Common Follow-up:**\n\"Can I use `useSyncExternalStore` with a Context-based store?\" (Yes, but context already works with concurrent rendering)\n\n**Real-world Example:**\nA real-time dashboard that subscribes to a WebSocket-based data store. Without `useSyncExternalStore`, concurrent updates may show inconsistent data (tearing). This hook ensures consistent snapshots.\n\n**Advanced Notes:**\nTearing occurs when external store changes during the rendering phase and a component sees two different values for the same store. `useSyncExternalStore` forces React to read the snapshot again in commit phase and re-render if mismatch. The hook is also used by React's own `useTransition` for shared mutable data.",[477,397,478,479],"useSyncExternalStore","external-store","tearing",{"id":481,"category":58,"question":482,"answer":483,"level":363,"tags":484},62,"What are the new features in React 19? Discuss the `use` hook, improvements in Server Components, and other updates.","**Concept Explanation:**\nReact 19 is expected to introduce several major features: the `use` hook (for promises and contexts without conditional rules), stable Server Components, `react-forget` (compiler) perhaps later, asset loading improvements, and actions (form actions). While React 19 is not yet stable, these features aim to simplify data fetching, reduce boilerplate, and improve performance.\n\n**Key Features:**\n- **`use` hook:** Can be called conditionally and inside loops; unwraps promises and context. Returns the resolved value, triggering suspense.\n- **Stable Server Components:** Full support for `async` components, zero-bundle-size.\n- **Actions (`useActionState`, `useFormStatus`):** Simplify form handling with pending states and optimistic updates.\n- **Asset loading:** `preload`, `preinit` APIs for fonts, scripts, styles.\n- **Document Metadata:** `\u003Ctitle>`, `\u003Cmeta>` directly in components.\n\n**Code Example (Use hook):**\n```jsx\nimport { use, Suspense } from 'react';\n\nfunction Comments({ commentsPromise }) {\n  const comments = use(commentsPromise); \u002F\u002F unwraps promise\n  return comments.map(c => \u003Cdiv key={c.id}>{c.text}\u003C\u002Fdiv>);\n}\n\nfunction Page() {\n  const commentsPromise = fetchComments();\n  return (\n    \u003CSuspense fallback={\u003Cdiv>Loading comments...\u003C\u002Fdiv>}>\n      \u003CComments commentsPromise={commentsPromise} \u002F>\n    \u003C\u002FSuspense>\n  );\n}\n```\n\n**Form Actions:**\n```jsx\n'use client';\nimport { useActionState } from 'react';\n\nasync function submitForm(prevState, formData) {\n  const name = formData.get('name');\n  await saveToDatabase(name);\n  return { success: true };\n}\n\nfunction Form() {\n  const [state, formAction, isPending] = useActionState(submitForm, null);\n  return (\n    \u003Cform action={formAction}>\n      \u003Cinput name=\"name\" \u002F>\n      \u003Cbutton type=\"submit\" disabled={isPending}>Submit\u003C\u002Fbutton>\n      {isPending && \u003Cp>Submitting...\u003C\u002Fp>}\n      {state?.success && \u003Cp>Success!\u003C\u002Fp>}\n    \u003C\u002Fform>\n  );\n}\n```\n\n**Document Metadata:**\n```jsx\nfunction BlogPost({ title, description }) {\n  return (\n    \u003C>\n      \u003Ctitle>{title}\u003C\u002Ftitle>\n      \u003Cmeta name=\"description\" content={description} \u002F>\n      \u003Carticle>...\u003C\u002Farticle>\n    \u003C\u002F>\n  );\n}\n```\n\n**Server Components (Async):**\n```jsx\n\u002F\u002F ServerComponent.server.js\nexport default async function ProductList() {\n  const products = await db.product.findMany();\n  return products.map(p => \u003Cdiv key={p.id}>{p.name}\u003C\u002Fdiv>);\n}\n```\n\n**Execution Flow:**\n- `use` hook suspends like `throw promise` but can be used conditionally.\n- Form actions handle submission with built-in pending state and progressive enhancement.\n- Metadata is collected by frameworks and inserted into `\u003Chead>`.\n\n**Practical Usage:**\n- Replace `useEffect`+`useState` for data fetching with `use` + Suspense.\n- Simplify forms with less boilerplate.\n- Improve SEO with document metadata components.\n\n**Common Mistakes:**\n- Using `use` without Suspense boundary (causes error).\n- Expecting `use` to work with raw values (only works with promises or contexts).\n\n**Interview Follow-ups:**\n- How does `use` differ from `useContext`?\n- Will `use` replace `useState`? (No, different purpose)\n- What is progressive enhancement in React forms?\n\n**Best Practices:**\n- Use `use` for data fetching in client components with Suspense.\n- Use form actions for mutations with built-in loading states.\n- Adopt Server Components for data-heavy views.\n\n**Performance Considerations:**\n- `use` simplifies concurrent data fetching but requires Suspense.\n- Form actions reduce client-side JavaScript for basic forms.\n\n**Production Recommendations:**\n- Wait for stable React 19 before adopting in production.\n- Use frameworks like Next.js that implement these features early.\n\n**Node.js \u002F SSR Behavior:**\n`use` works on server with promises; form actions work with progressive enhancement.\n\n**Latest React Patterns:**\n- React 19 integrates closely with Next.js App Router.\n- `use` may also work with context.\n\n**TypeScript Example:**\n```tsx\ntype State = { success: boolean } | null;\nconst [state, action, pending] = useActionState\u003CState, FormData>(submit, null);\n```\n\n**Interview Tip:**\nExplain that React 19 aims to simplify async operations and reduce client bundle size. The `use` hook is a game-changer for data fetching.\n\n**Common Follow-up:**\n\"Will `use` be the only way to consume promises in React?\" (Not the only, but recommended)\n\n**Real-world Example:**\nA blog post component that fetches comments asynchronously. With `use`, you can pass a promise and let Suspense handle loading, without manually managing loading states.\n\n**Advanced Notes:**\nReact 19 may also include a caching mechanism (`cache` function) for deduplicating requests. The `use` hook also works with context, providing a conditional alternative to `useContext`. Form actions integrate with `useOptimistic` for optimistic updates.",[485,486,487,433],"react-19","use","actions",{"id":489,"category":360,"question":490,"answer":491,"level":363,"tags":492},63,"How does React's cache mechanism work for data fetching and what problems does it solve?","**Concept Explanation:**\nReact's `cache` function (unstable in React 18, expected stable in React 19) is used to deduplicate asynchronous data fetching across multiple components that request the same data. It caches the promise for a given input arguments and returns the same promise to concurrent callers, preventing duplicate network requests and ensuring consistent data.\n\n**How It Works:**\n- `cache` wraps an async function.\n- It maintains a per-request cache (or per-render cache in Server Components).\n- When the cached function is called with the same arguments, it returns the previously created promise instead of creating a new one.\n- The cache lives for the duration of the request (SSR) or until component unmount (client).\n\n**Code Example:**\n```jsx\nimport { cache } from 'react';\n\n\u002F\u002F Server-side (or client with stable cache)\nconst getUser = cache(async (userId) => {\n  const user = await db.user.findUnique({ where: { id: userId } });\n  return user;\n});\n\nfunction UserProfile({ userId }) {\n  const user = await getUser(userId);\n  return \u003Cdiv>{user.name}\u003C\u002Fdiv>;\n}\n\nfunction UserPosts({ userId }) {\n  const user = await getUser(userId); \u002F\u002F same user data, no duplicate fetch\n  return \u003Cdiv>Posts by {user.name}\u003C\u002Fdiv>;\n}\n\n\u002F\u002F With Suspense (client)\nimport { cache, Suspense } from 'react';\n\nconst fetchUser = cache(async (id) => {\n  const res = await fetch(`\u002Fapi\u002Fusers\u002F${id}`);\n  return res.json();\n});\n\nfunction User({ id }) {\n  const user = use(fetchUser(id)); \u002F\u002F using `use` with cached promise\n  return \u003Cdiv>{user.name}\u003C\u002Fdiv>;\n}\n```\n\n**Execution Flow:**\n1. Component A calls `getUser(1)`, cache creates a promise and stores it.\n2. Component B calls `getUser(1)` before promise resolves; cache returns the same promise.\n3. Both components suspend using that promise.\n4. When promise resolves, both components resume with same data.\n\n**Reactivity Explanation:**\nCache ensures data consistency across components without extra network calls.\n\n**Practical Usage:**\n- Server Components: share data between different parts of the tree without passing props.\n- Client components: deduplicate API requests for same query parameters.\n- Combined with `use` and Suspense for clean data fetching.\n\n**Common Mistakes:**\n- Using `cache` with non-deterministic functions (e.g., random).\n- Expecting cache to persist across page navigations (not guaranteed).\n- Not using stable cache keys (function arguments must be serializable).\n\n**Interview Follow-ups:**\n- How does `cache` differ from `React.memo`?\n- Does `cache` work across different users? (No, per request\u002Fcomponent tree)\n- Can you use `cache` in client components?\n\n**Best Practices:**\n- Use `cache` for data fetching functions that are idempotent.\n- Combine with `use` for async consumption.\n- In Server Components, `cache` is a key pattern for performance.\n\n**Performance Considerations:**\n- Prevents waterfall requests.\n- Reduces server load (in SSR).\n- Adds small overhead for cache lookup.\n\n**Production Recommendations:**\n- Use in Next.js App Router for server components.\n- For client, ensure your data fetching library doesn't already deduplicate (React Query does).\n\n**Node.js \u002F SSR Behavior:**\n`cache` is most useful on server; on client, it's limited to the component tree's lifetime.\n\n**Latest React Patterns:**\n- React 19 will likely stabilize `cache`.\n- Used heavily in Next.js's `fetch` deduplication.\n\n**TypeScript Example:**\n```tsx\nconst getData = cache(async (key: string): Promise\u003CData> => {\n  const res = await fetch(`\u002Fapi\u002F${key}`);\n  return res.json();\n});\n```\n\n**Interview Tip:**\nExplain that `cache` solves the problem of duplicate data requests when multiple components need the same data. It's like a memoization for async functions.\n\n**Common Follow-up:**\n\"How does `cache` differ from React Query's caching?\" (React Query has time-based invalidation, cross-component; `cache` is per-request\u002Frender)\n\n**Real-world Example:**\nA dashboard showing user profile, recent orders, and user stats. Each component needs user info; without cache, three requests. With cache, only one request.\n\n**Advanced Notes:**\n`cache` uses the `WeakMap` internally, keyed by the arguments and a per-request context. In Server Components, cache persists for the entire request. In client, it persists while the component tree is mounted. `cache` also works with `useMemo`-like patterns but for async operations.",[493,113,494,485],"cache","deduplication",{"id":496,"category":497,"question":498,"answer":499,"level":363,"tags":500},64,"Design Patterns","Explain advanced React patterns: Higher-Order Components (HOC), Render Props, and Custom Hooks. Compare their trade-offs.","**Concept Explanation:**\nThese three patterns all aim to reuse logic across components. HOCs wrap a component, returning an enhanced component. Render props pass a function as a child that returns JSX. Custom hooks extract stateful logic into reusable functions. Hooks are now the recommended approach, but understanding all patterns is valuable for legacy codebases.\n\n**Higher-Order Component (HOC):**\n```jsx\nfunction withLogger(WrappedComponent) {\n  return function WithLogger(props) {\n    useEffect(() => console.log('Props:', props), [props]);\n    return \u003CWrappedComponent {...props} \u002F>;\n  };\n}\n\nconst EnhancedComponent = withLogger(MyComponent);\n\u002F\u002F Trade-offs: props naming collisions, static typing issues (withForwardRef), wrapper hell.\n```\n\n**Render Props:**\n```jsx\nfunction MouseTracker({ children }) {\n  const [position, setPosition] = useState({ x: 0, y: 0 });\n  useEffect(() => {\n    const handleMove = (e) => setPosition({ x: e.clientX, y: e.clientY });\n    window.addEventListener('mousemove', handleMove);\n    return () => window.removeEventListener('mousemove', handleMove);\n  }, []);\n  return children(position);\n}\n\n\u002F\u002F Usage\n\u003CMouseTracker>{({ x, y }) => \u003Cdiv>Mouse at {x},{y}\u003C\u002Fdiv>}\u003C\u002FMouseTracker>\n\u002F\u002F Trade-offs: callback hell if nested, less performant due to inline functions.\n```\n\n**Custom Hook (modern):**\n```jsx\nfunction useMouse() {\n  const [position, setPosition] = useState({ x: 0, y: 0 });\n  useEffect(() => {\n    const handler = (e) => setPosition({ x: e.clientX, y: e.clientY });\n    window.addEventListener('mousemove', handler);\n    return () => window.removeEventListener('mousemove', handler);\n  }, []);\n  return position;\n}\n\n\u002F\u002F Usage\nconst { x, y } = useMouse();\n\u002F\u002F Trade-offs: simpler, no nesting, easy to compose, but hooks have rules.\n```\n\n**Comparison Table:**\n| Pattern | Composition | Performance | Typing | Nesting | Readability |\n|---------|-------------|-------------|--------|---------|-------------|\n| HOC | difficult | good | complex | wrapper hell | medium |\n| Render Props | good | fair | okay | callback pyramid | good |\n| Custom Hooks | excellent | best | easy | flat | excellent |\n\n**Code Example (compose multiple hooks):**\n```jsx\nfunction useUserAndPosts(userId) {\n  const user = useUser(userId);\n  const posts = usePosts(userId);\n  return { user, posts };\n}\n\u002F\u002F Easy composition, no wrapper nesting.\n```\n\n**Practical Usage:**\n- HOC: Legacy code, libraries like `connect` (Redux), `withRouter` (React Router v5).\n- Render props: React Router v5 `\u003CRoute>`, `react-measure`.\n- Custom hooks: All new code, `useQuery`, `useFetch`, `useLocalStorage`.\n\n**Common Mistakes:**\n- HOC: Passing refs through (need `forwardRef`).\n- Render props: Inline functions causing re-renders.\n- Custom hooks: Breaking rules of hooks (conditional calls).\n\n**Interview Follow-ups:**\n- Why did React introduce hooks? (To replace HOCs and render props with simpler composition)\n- Can you implement a custom hook that uses another custom hook? (Yes)\n- When would you still use a HOC today? (Error boundaries, third-party libraries)\n\n**Best Practices:**\n- Use custom hooks for new development.\n- Prefer hooks over HOCs and render props.\n- For HOCs, ensure static hoisting (`hoist-non-react-statics`).\n\n**Performance Considerations:**\n- HOCs may add extra components to tree but minimal overhead.\n- Render props with inline functions can cause child re-renders (use `useCallback`).\n- Custom hooks have the same performance as built-in hooks.\n\n**Production Recommendations:**\n- Migrate HOCs and render props to custom hooks when possible.\n- Use libraries that already provide hooks (React Router v6 uses hooks).\n\n**Node.js \u002F SSR Behavior:**\nAll patterns work on server; custom hooks are simplest.\n\n**Latest React Patterns:**\n- React 18+ promotes hooks and Server Components (which cannot use hooks).\n- Hooks may not be used in Server Components; HOCs and render props can be used but with care.\n\n**TypeScript Example:**\n```tsx\ntype MousePosition = { x: number; y: number };\nfunction useMouse(): MousePosition { ... }\n```\n\n**Interview Tip:**\nExplain that custom hooks are the most modern and flexible pattern, but you need to recognize HOCs and render props when working with older codebases.\n\n**Common Follow-up:**\n\"Can you convert a HOC to a custom hook?\" (Sometimes, not always – HOCs can also manipulate rendered output, hooks only logic)\n\n**Real-world Example:**\nRedux `connect` HOC vs `useSelector` hook. The hook is simpler and less error-prone.\n\n**Advanced Notes:**\nHOCs and render props are still useful when you need to control rendering (e.g., authentication wrapper) rather than just logic. However, composition with hooks is generally superior. React's future Server Components may need render props because hooks are unavailable there.",[501,330,231,502],"hoc","design-patterns",{"id":504,"category":505,"question":506,"answer":507,"level":363,"tags":508},65,"Accessibility","How do you build accessible React components? Discuss ARIA, keyboard navigation, focus management, and testing.","**Concept Explanation:**\nAccessibility (a11y) in React involves using semantic HTML, ARIA attributes where needed, managing focus, and ensuring keyboard navigation. React supports standard HTML attributes, including `aria-*`. Tools like `eslint-plugin-jsx-a11y` catch common issues. Focus management is critical for modals, menus, and form validation.\n\n**Semantic HTML:**\n```jsx\n\u002F\u002F Good\n\u003Cbutton onClick={handleClick}>Submit\u003C\u002Fbutton>\n\u003Ch1>Main heading\u003C\u002Fh1>\n\u003Cnav>\u003Cul>\u003Cli>\u003Ca href=\"\u002F\">Home\u003C\u002Fa>\u003C\u002Fli>\u003C\u002Ful>\u003C\u002Fnav>\n\n\u002F\u002F Bad (div as button)\n\u003Cdiv onClick={handleClick} role=\"button\" tabIndex={0}>Submit\u003C\u002Fdiv>\n```\n\n**ARIA Attributes:**\n```jsx\n\u003Cdiv role=\"dialog\" aria-labelledby=\"dialog-title\" aria-describedby=\"dialog-desc\">\n  \u003Ch2 id=\"dialog-title\">Confirm\u003C\u002Fh2>\n  \u003Cp id=\"dialog-desc\">Do you want to delete?\u003C\u002Fp>\n  \u003Cbutton onClick={onConfirm}>Yes\u003C\u002Fbutton>\n\u003C\u002Fdiv>\n```\n\n**Focus Management (useRef and useEffect):**\n```jsx\nimport { useRef, useEffect } from 'react';\n\nfunction Modal({ isOpen, onClose }) {\n  const modalRef = useRef(null);\n  const previousFocus = useRef(null);\n\n  useEffect(() => {\n    if (isOpen) {\n      previousFocus.current = document.activeElement;\n      modalRef.current?.focus();\n      return () => previousFocus.current?.focus();\n    }\n  }, [isOpen]);\n\n  const handleKeyDown = (e) => {\n    if (e.key === 'Escape') onClose();\n    if (e.key === 'Tab') {\n      \u002F\u002F trap focus inside modal\n      const focusable = modalRef.current.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex=\"-1\"])');\n      const first = focusable[0];\n      const last = focusable[focusable.length - 1];\n      if (e.shiftKey && document.activeElement === first) {\n        last.focus();\n        e.preventDefault();\n      } else if (!e.shiftKey && document.activeElement === last) {\n        first.focus();\n        e.preventDefault();\n      }\n    }\n  };\n\n  if (!isOpen) return null;\n  return (\n    \u003Cdiv\n      ref={modalRef}\n      role=\"dialog\"\n      aria-modal=\"true\"\n      tabIndex={-1}\n      onKeyDown={handleKeyDown}\n    >\n      \u003Cbutton onClick={onClose}>Close\u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  );\n}\n```\n\n**Testing Accessibility:**\n```jsx\nimport { render, screen } from '@testing-library\u002Freact';\nimport { axe, toHaveNoViolations } from 'jest-axe';\n\nexpect.extend(toHaveNoViolations);\n\nit('should have no accessibility violations', async () => {\n  const { container } = render(\u003CMyComponent \u002F>);\n  const results = await axe(container);\n  expect(results).toHaveNoViolations();\n});\n```\n\n**Keyboard Navigation:**\n- Use `onKeyDown` for custom keyboard handlers.\n- Ensure all interactive elements are reachable with Tab.\n- Use `role` and `aria` to convey state.\n\n**Common Mistakes:**\n- Missing `alt` on images.\n- Using `onClick` on non-interactive elements without keyboard handlers.\n- Not managing focus in modals\u002Fnotifications.\n- Relying solely on color to convey information.\n\n**Interview Follow-ups:**\n- What is the difference between `aria-label` and `aria-labelledby`?\n- How do you test for accessibility in CI?\n- What is focus trapping and when is it needed?\n\n**Best Practices:**\n- Start with semantic HTML; add ARIA only when needed.\n- Use `eslint-plugin-jsx-a11y` to catch issues.\n- Test with screen readers (NVDA, VoiceOver).\n- Use `:focus-visible` CSS for visible focus indicators.\n\n**Performance Considerations:**\n- ARIA attributes add no performance penalty.\n- Focus management may cause re-renders but negligible.\n\n**Production Recommendations:**\n- Automate a11y tests with `jest-axe`.\n- Include accessibility requirements in code reviews.\n- Use React components from accessible libraries (React Aria, Reach UI).\n\n**Node.js \u002F SSR Behavior:**\nAccessibility attributes are rendered as part of HTML; no special server handling.\n\n**Latest React Patterns:**\n- React Aria (Adobe) provides hooks for accessible components.\n- `useId` for generating unique IDs for `aria-labelledby`.\n\n**TypeScript Example:**\n```tsx\nconst modalRef = useRef\u003CHTMLDivElement>(null);\n```\n\n**Interview Tip:**\nExplain that accessibility is a priority, not an afterthought. React doesn't add special a11y features, but it doesn't hinder them either.\n\n**Common Follow-up:**\n\"What is the purpose of `aria-hidden`?\" (Hides content from screen readers, used for decorative elements)\n\n**Real-world Example:**\nA custom dropdown component must be keyboard accessible: arrow keys to navigate, Enter to select, Escape to close, and proper ARIA roles (`combobox`, `listbox`, `option`).\n\n**Advanced Notes:**\nWCAG 2.1 success criteria should be referenced. React's `createRoot` does not affect a11y. `role` attributes can be overridden, but avoid over-using ARIA when HTML semantics suffice. Focus management is critical for single-page applications to not lose user context.",[509,510,511,512,344],"accessibility","aria","keyboard","focus",1779734543422]