react 53 Q&As

React FAQ & Answers

53 expert React answers researched from official documentation. Every answer cites authoritative sources you can verify.

unknown

52 questions
A

React is a JavaScript library for building user interfaces, developed by Meta. Core principles: (1) Component-based architecture - UI built from reusable components, (2) Declarative - describe what UI should look like, React handles updates, (3) Fiber reconciliation - efficient incremental rendering with priority-based updates, (4) Unidirectional data flow - props flow down, events bubble up, (5) Learn once, write anywhere - React Native for mobile/desktop. React 19 (2024) adds Server Components for server-first rendering and the React Compiler for automatic memoization. Modern React emphasizes function components with Hooks over classes.

99% confidence
A

Hooks are functions that let you use React features (state, lifecycle, context) in function components without classes. Introduced React 16.8 (2019). Built-in hooks: useState, useEffect, useContext, useReducer, useCallback, useMemo, useRef, useTransition (React 18), useDeferredValue (React 18), useId (React 18). Benefits: simpler code, better code reuse (custom hooks), no 'this' confusion, easier testing, logic grouping by concern not lifecycle, seamless concurrent features. Rules: only call at top level, only in React functions. React 19 adds useActionState and useOptimistic for server actions. Hooks are now the standard way to write React components.

99% confidence
A

useState adds state to function components. Syntax: const [value, setValue] = useState(initialValue). Returns array: current state and setter function. Initial value used only on first render (can be function for lazy initialization). Setter can take new value or updater function (prev => prev + 1) for state based on previous. Multiple useState calls for different state variables. React 18+ automatic batching batches all state updates (events, promises, timeouts) for better performance. State persists between re-renders. Use startTransition for non-urgent updates. Fundamental hook for interactive components.

99% confidence
A

useEffect runs side effects after render: data fetching, subscriptions, DOM manipulation, timers. Syntax: useEffect(() => { /* effect / return () => { / cleanup */ }}, [dependencies]). Dependency array controls when it runs: [] runs once (mount), [dep] runs when dep changes, omitted runs every render. Always return cleanup function to prevent memory leaks - cleanup runs with old values before re-running effect and on unmount. React 18+ Strict Mode runs effects twice in dev to catch missing cleanup. 2025 best practices: use useSyncExternalStore for subscriptions, React Query/SWR for data fetching, keep dependencies narrow, ensure cleanup mirrors setup for idempotence.

99% confidence
A

Context provides way to pass data through component tree without prop drilling. Create context: const MyContext = React.createContext(defaultValue). Provider: <MyContext.Provider value={data}>. Consumer: const value = useContext(MyContext). useContext returns current context value from nearest Provider above. When value changes, all consumers re-render. 2025 optimization: split state and dispatch into separate contexts to prevent unnecessary re-renders, wrap value in useMemo, stabilize provider children. Use for: themes, auth, language. For complex global state, prefer Zustand (3KB, simple) or Jotai (atomic state). Don't optimize prematurely - measure first.

99% confidence
A

Both optimize performance by memoizing values. useCallback memoizes functions: const memoizedCallback = useCallback(() => doSomething(a, b), [a, b]). Returns same function reference until dependencies change. useMemo memoizes computed values: const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]). Re-computes only when dependencies change. Use useCallback to prevent child re-renders when passing callbacks to React.memo components. Use useMemo for expensive calculations (>50ms). Note: React Compiler (React 19+) can auto-memoize, reducing manual useCallback/useMemo needs. Don't optimize prematurely - measure first with React DevTools Profiler.

99% confidence
A

useRef returns mutable ref object: const ref = useRef(initialValue). ref.current persists across renders without causing re-renders. Use cases: (1) DOM access -

, then myRef.current.focus(), scrollIntoView(), etc., (2) Store mutable values (timers, intervals, previous values), (3) Third-party library integration. Callback refs for dynamic elements: <div ref={node => { if (node) measureNode(node) }}>. Unlike state, updating ref doesn't trigger re-render. Don't read/write ref.current during render - only in effects or event handlers. Essential escape hatch for imperative code in declarative React.

99% confidence
A

useReducer manages complex state logic: const [state, dispatch] = useReducer(reducer, initialState). Reducer: (state, action) => newState. Dispatch actions to update state. Similar to Redux pattern. Use when: state has multiple sub-values, next state depends on previous, complex state transitions, multiple event handlers update same state. Benefits: centralized logic, easier testing, predictable updates, dispatch stable across renders. useState for simple state, useReducer for complex local state. For global state, consider Zustand (90% of apps) or Redux Toolkit (enterprise apps with strict patterns) instead of useReducer + Context.

99% confidence
A

Keys help React's Fiber reconciler identify which items changed, added, or removed in lists. Must be unique among siblings (not globally). Use stable IDs from data, not array indexes (causes issues with reordering, filtering, insertion). React uses keys to match old Fiber nodes to new ones during reconciliation - preserving component state and DOM nodes. Without keys or with bad keys (indexes), React may incorrectly reuse elements, causing bugs (wrong state, lost focus, incorrect animations). Example: items.map(item => ). Never use Math.random() (regenerates) or index when list can change. Keys are critical for list performance and correctness.

99% confidence
A

Virtual DOM is lightweight JavaScript object tree representing your UI. React creates virtual tree on each render. Reconciliation is React's diffing algorithm that compares old and new virtual trees to compute minimal DOM updates. Fiber architecture (React 16-19) enables incremental rendering, work prioritization, and concurrent features. Process: render phase (pure, interruptible, builds Fiber tree) and commit phase (applies DOM updates, runs effects). Each component is a Fiber node (unit of work). Keys help match elements across renders. React 19 integrates with React Compiler for automatic memoization, minimizing re-renders. Benefits: performance (batch updates), cross-platform (React Native), concurrent rendering.

99% confidence
A

Controlled: React state is source of truth. Input value from state, onChange updates state. Full control, easy validation, conditional logic. Example: <input value={value} onChange={e => setValue(e.target.value)} />. Uncontrolled: DOM is source of truth. Access with refs. Less code, useful for non-React integration, file inputs always uncontrolled. Example: . 2025 best practice: use React Hook Form (controlled with minimal re-renders) or Formik for complex forms. Combine with Zod or Yup for type-safe validation. Use controlled for most forms, uncontrolled for simple cases.

99% confidence
A

Prop drilling: passing props through multiple component levels to reach deep children. Problems: verbose, hard to maintain, couples components. Solutions ranked by preference: (1) Component composition - pass components as children/props to avoid drilling (best first choice), (2) State colocation - move state closer to where it's used, (3) Zustand - simple global state (3KB, no provider hell), (4) Context API - for themes/auth/i18n, (5) Jotai - atomic state for fine-grained control, (6) Redux Toolkit - enterprise apps needing strict patterns. 2025 recommendation: composition first, then Zustand for 90% of apps. Avoid Context for frequently-changing data.

99% confidence
A

Fragments let you group children without adding DOM nodes. Syntax: ... or <>...</>. Use when: component must return single element but don't want wrapper div, mapping to elements needing keys (), table rows/cells (avoid invalid HTML), avoiding CSS flexbox/grid layout issues from wrapper divs. Benefits: cleaner DOM, avoid styling issues from wrappers, semantic HTML, better accessibility. Key syntax: <React.Fragment key={id}> (shorthand <> doesn't support keys). Fragments are zero-cost abstractions - compiled away, no performance impact. Use liberally to avoid unnecessary DOM nesting.

Sources
99% confidence
A

React.memo is higher-order component for memoization. Prevents re-renders when props unchanged (shallow comparison). Usage: const MemoizedComponent = React.memo(Component). Custom comparison: React.memo(Component, (prevProps, nextProps) => /* return true if equal */). Only re-renders if props change. Use for: expensive render components (>50ms), frequently re-rendered leaf components with same props. Don't use everywhere - has comparison cost. Combine with useCallback/useMemo for prop stability (functions/objects). Profile with React DevTools Profiler before optimizing. Note: React Compiler (React 19+) auto-memoizes components, reducing manual React.memo needs. Class equivalent: PureComponent.

99% confidence
A

Error Boundaries catch JavaScript errors in child component tree, log errors, display fallback UI. Class implementation: componentDidCatch(error, info) and static getDerivedStateFromError(error). No native function component equivalent yet. Catches: render errors, lifecycle methods, constructors. Doesn't catch: event handlers (use try/catch), async code, SSR errors, errors in boundary itself. 2025 best practice: use react-error-boundary library (npm install react-error-boundary) for function components with useErrorBoundary hook. Example: . Hook lets you pass errors from event handlers/async code to nearest boundary. Essential for production resilience.

99% confidence
A

Code splitting loads components on-demand, reducing initial bundle size. React.lazy + Suspense: const Component = React.lazy(() => import('./Component')). Wrap with Suspense: <Suspense fallback={}>. Only works with default exports (or use export { Component as default }). Route-based splitting most impactful: lazy load routes with React Router/Next.js. Modern bundlers (Vite, Turbopack, Webpack 5) handle automatic chunking. Benefits: faster Time-to-Interactive, better Core Web Vitals. React 19 enhances Suspense with better streaming, asset loading coordination. Use for: routes (highest impact), modals/dialogs, tabs, admin panels, rarely-used features. Measure with Lighthouse/WebPageTest.

99% confidence
A

Custom hooks extract component logic into reusable functions. Naming: must start with 'use' (linter enforces). Can call other hooks. Example: function useLocalStorage(key: string, initial: T) { const [value, setValue] = useState(() => JSON.parse(localStorage.getItem(key) || JSON.stringify(initial))); useEffect(() => localStorage.setItem(key, JSON.stringify(value)), [key, value]); return [value, setValue] as const; }. Benefits: logic reuse across components, cleaner components, testable in isolation, composable. Share stateful logic, not state itself (each component gets own state). Follow hook rules (top-level, React functions only). Popular libraries: usehooks-ts, react-use. TypeScript highly recommended.

99% confidence
A

JSX is syntax extension for JavaScript that looks like HTML. JSX elements are transformed to JavaScript by Babel/TypeScript. Modern transform (React 17+): automatic JSX runtime, no need to import React. Old: React.createElement('div', null, 'Hello'). New: _jsx('div', { children: 'Hello' }). Expressions in {}: {variable}, {fn()}, {condition ? a : b}, {array.map()}. JSX prevents XSS attacks (auto-escapes values). Closer to JavaScript than HTML: className not class, htmlFor not for, camelCase event handlers (onClick), style={{}} object, self-closing tags required. JSX is optional but industry standard. TypeScript provides excellent JSX type checking.

99% confidence
A

Both are base classes for class components (legacy pattern). Component: re-renders when setState called or parent re-renders, no optimization. PureComponent: implements shouldComponentUpdate with shallow prop/state comparison, skips re-render if unchanged - equivalent to React.memo for classes. PureComponent has comparison cost but saves render cost. Pitfall: shallow comparison misses nested object changes (must use immutable updates). 2025 best practice: migrate to function components with hooks. Use React.memo instead of PureComponent, useState instead of setState, useEffect instead of lifecycle methods. Class components still supported but not recommended for new code. Legacy codebases can migrate incrementally.

99% confidence
A

is development-only tool highlighting potential problems. No production overhead (completely stripped). Enables: (1) Identifies unsafe lifecycles, (2) Warns about legacy string refs and findDOMNode, (3) Detects unexpected side effects via double-invocation (components, effects, state initializers), (4) Warns about deprecated APIs. React 18+: double-renders components and double-runs effects in dev to catch missing cleanup and non-idempotent code. React 19: enhanced checks for Server Components, async rendering issues. Wrap app: . Essential for production-ready code. If third-party library breaks, report issue or wrap only your code.

99% confidence
A

Portals render children into DOM node outside parent component hierarchy while preserving React tree position. Use ReactDOM.createPortal(children, domNode, key?). Common use cases: modals/dialogs, tooltips, popovers, dropdowns, notifications - elements that need to escape parent's overflow:hidden, z-index stacking, or CSS containment. Example: createPortal({children}, document.body). Events bubble through React tree (not DOM tree), context works normally, state/props flow naturally. Accessibility: manage focus trap, ARIA, ESC key handling. Modern alternative: CSS dialog element with showModal(). Portals essential for overlay UI avoiding CSS layout constraints and ensuring proper layering.

Sources
99% confidence
A

Concurrent rendering allows React to interrupt rendering, prioritize updates, work on multiple state versions simultaneously. React 18 features: automatic batching (all updates batched, even in promises/timeouts), transitions (useTransition/startTransition for non-urgent updates), Suspense for data fetching, useDeferredValue for deprioritizing expensive renders. Benefits: UI stays responsive during expensive operations, prioritize urgent updates (typing) over expensive (search results), smoother animations, better perceived performance. Opt-in: use createRoot() instead of ReactDOM.render(). React 19 enhances with full Server Components support, better streaming SSR, improved Suspense coordination. Backwards compatible - concurrent features opt-in. Fundamental shift enabling responsive UIs at scale.

99% confidence
A

Client-Side Rendering (CSR): React runs in browser, JavaScript builds UI, slower Time-to-Interactive, SEO challenges (crawlable but not optimal), full client-side control. Server-Side Rendering (SSR): React renders HTML on server, faster First Contentful Paint, better SEO/crawlability, requires hydration (client takes over). Static Site Generation (SSG): pre-render at build time, fastest option, limited dynamic data. React Server Components (RSC, React 19): server-only components with zero client JS, async/await in components, direct database access, seamless client/server composition. 2025 best practice: Next.js App Router (RSC by default) or Remix for full-stack apps. RSC reduces bundle size 40%+, improves TTI by 340ms. Hybrid approach: RSC for static content, client components ('use client') for interactivity.

99% confidence
A

Refs store values that persist across renders without triggering re-renders. Use refs for: (1) DOM manipulation - focus(), scrollIntoView(), play/pause video, measuring elements, (2) Storing mutable values - timer IDs, intervals, previous values, request IDs, (3) Third-party integration - Canvas, D3, maps, non-React widgets. Use state for: data that affects what renders, UI state, form inputs, toggles, counters. Key difference: changing ref.current doesn't re-render, changing state does. Don't read/write ref.current during render - only in effects/event handlers. Callback refs for dynamic elements: <div ref={node => node && measure(node)}>. Prefer declarative React patterns over imperative refs when possible.

99% confidence
A

React uses SyntheticEvent wrapper for cross-browser compatibility and consistent behavior. Attach handlers via camelCase props: onClick={handleClick}, onChange={handleChange}, onMouseOver={handleMouseOver}. SyntheticEvent provides same interface across browsers with stopPropagation() and preventDefault() methods. Event pooling removed in React 17+ for better performance. In function components, event handlers are automatically bound to component instance. Use arrow functions or useCallback to optimize performance. Events bubble up through component hierarchy by default. SyntheticEvent includes nativeEvent property for browser-specific access.

99% confidence
A

React implements event delegation by attaching one event listener per event type at the container level (root in React 17+, document in earlier versions), not individual elements. When event fires, React uses event bubbling to determine which component triggered it and calls appropriate handler. Benefits: reduced memory usage, faster initial render, easier cleanup. Critical for lists with many items - 1000 items with click handlers use 1 listener instead of 1000. Works with dynamic content - new elements automatically get event handling. Capture phase available via onClickCapture prop. Essential for React's performance with large applications.

99% confidence
A

React is a JavaScript library for building user interfaces, developed by Meta. Core principles: (1) Component-based architecture - UI built from reusable components, (2) Declarative - describe what UI should look like, React handles updates, (3) Fiber reconciliation - efficient incremental rendering with priority-based updates, (4) Unidirectional data flow - props flow down, events bubble up, (5) Learn once, write anywhere - React Native for mobile/desktop. React 19 (2024) adds Server Components for server-first rendering and the React Compiler for automatic memoization. Modern React emphasizes function components with Hooks over classes.

99% confidence
A

Hooks are functions that let you use React features (state, lifecycle, context) in function components without classes. Introduced React 16.8 (2019). Built-in hooks: useState, useEffect, useContext, useReducer, useCallback, useMemo, useRef, useTransition (React 18), useDeferredValue (React 18), useId (React 18). Benefits: simpler code, better code reuse (custom hooks), no 'this' confusion, easier testing, logic grouping by concern not lifecycle, seamless concurrent features. Rules: only call at top level, only in React functions. React 19 adds useActionState and useOptimistic for server actions. Hooks are now the standard way to write React components.

99% confidence
A

useState adds state to function components. Syntax: const [value, setValue] = useState(initialValue). Returns array: current state and setter function. Initial value used only on first render (can be function for lazy initialization). Setter can take new value or updater function (prev => prev + 1) for state based on previous. Multiple useState calls for different state variables. React 18+ automatic batching batches all state updates (events, promises, timeouts) for better performance. State persists between re-renders. Use startTransition for non-urgent updates. Fundamental hook for interactive components.

99% confidence
A

useEffect runs side effects after render: data fetching, subscriptions, DOM manipulation, timers. Syntax: useEffect(() => { /* effect / return () => { / cleanup */ }}, [dependencies]). Dependency array controls when it runs: [] runs once (mount), [dep] runs when dep changes, omitted runs every render. Always return cleanup function to prevent memory leaks - cleanup runs with old values before re-running effect and on unmount. React 18+ Strict Mode runs effects twice in dev to catch missing cleanup. 2025 best practices: use useSyncExternalStore for subscriptions, React Query/SWR for data fetching, keep dependencies narrow, ensure cleanup mirrors setup for idempotence.

99% confidence
A

Context provides way to pass data through component tree without prop drilling. Create context: const MyContext = React.createContext(defaultValue). Provider: <MyContext.Provider value={data}>. Consumer: const value = useContext(MyContext). useContext returns current context value from nearest Provider above. When value changes, all consumers re-render. 2025 optimization: split state and dispatch into separate contexts to prevent unnecessary re-renders, wrap value in useMemo, stabilize provider children. Use for: themes, auth, language. For complex global state, prefer Zustand (3KB, simple) or Jotai (atomic state). Don't optimize prematurely - measure first.

99% confidence
A

Both optimize performance by memoizing values. useCallback memoizes functions: const memoizedCallback = useCallback(() => doSomething(a, b), [a, b]). Returns same function reference until dependencies change. useMemo memoizes computed values: const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]). Re-computes only when dependencies change. Use useCallback to prevent child re-renders when passing callbacks to React.memo components. Use useMemo for expensive calculations (>50ms). Note: React Compiler (React 19+) can auto-memoize, reducing manual useCallback/useMemo needs. Don't optimize prematurely - measure first with React DevTools Profiler.

99% confidence
A

useRef returns mutable ref object: const ref = useRef(initialValue). ref.current persists across renders without causing re-renders. Use cases: (1) DOM access -

, then myRef.current.focus(), scrollIntoView(), etc., (2) Store mutable values (timers, intervals, previous values), (3) Third-party library integration. Callback refs for dynamic elements: <div ref={node => { if (node) measureNode(node) }}>. Unlike state, updating ref doesn't trigger re-render. Don't read/write ref.current during render - only in effects or event handlers. Essential escape hatch for imperative code in declarative React.

99% confidence
A

useReducer manages complex state logic: const [state, dispatch] = useReducer(reducer, initialState). Reducer: (state, action) => newState. Dispatch actions to update state. Similar to Redux pattern. Use when: state has multiple sub-values, next state depends on previous, complex state transitions, multiple event handlers update same state. Benefits: centralized logic, easier testing, predictable updates, dispatch stable across renders. useState for simple state, useReducer for complex local state. For global state, consider Zustand (90% of apps) or Redux Toolkit (enterprise apps with strict patterns) instead of useReducer + Context.

99% confidence
A

Keys help React's Fiber reconciler identify which items changed, added, or removed in lists. Must be unique among siblings (not globally). Use stable IDs from data, not array indexes (causes issues with reordering, filtering, insertion). React uses keys to match old Fiber nodes to new ones during reconciliation - preserving component state and DOM nodes. Without keys or with bad keys (indexes), React may incorrectly reuse elements, causing bugs (wrong state, lost focus, incorrect animations). Example: items.map(item => ). Never use Math.random() (regenerates) or index when list can change. Keys are critical for list performance and correctness.

99% confidence
A

Virtual DOM is lightweight JavaScript object tree representing your UI. React creates virtual tree on each render. Reconciliation is React's diffing algorithm that compares old and new virtual trees to compute minimal DOM updates. Fiber architecture (React 16-19) enables incremental rendering, work prioritization, and concurrent features. Process: render phase (pure, interruptible, builds Fiber tree) and commit phase (applies DOM updates, runs effects). Each component is a Fiber node (unit of work). Keys help match elements across renders. React 19 integrates with React Compiler for automatic memoization, minimizing re-renders. Benefits: performance (batch updates), cross-platform (React Native), concurrent rendering.

99% confidence
A

Controlled: React state is source of truth. Input value from state, onChange updates state. Full control, easy validation, conditional logic. Example: <input value={value} onChange={e => setValue(e.target.value)} />. Uncontrolled: DOM is source of truth. Access with refs. Less code, useful for non-React integration, file inputs always uncontrolled. Example: . 2025 best practice: use React Hook Form (controlled with minimal re-renders) or Formik for complex forms. Combine with Zod or Yup for type-safe validation. Use controlled for most forms, uncontrolled for simple cases.

99% confidence
A

Prop drilling: passing props through multiple component levels to reach deep children. Problems: verbose, hard to maintain, couples components. Solutions ranked by preference: (1) Component composition - pass components as children/props to avoid drilling (best first choice), (2) State colocation - move state closer to where it's used, (3) Zustand - simple global state (3KB, no provider hell), (4) Context API - for themes/auth/i18n, (5) Jotai - atomic state for fine-grained control, (6) Redux Toolkit - enterprise apps needing strict patterns. 2025 recommendation: composition first, then Zustand for 90% of apps. Avoid Context for frequently-changing data.

99% confidence
A

Fragments let you group children without adding DOM nodes. Syntax: ... or <>...</>. Use when: component must return single element but don't want wrapper div, mapping to elements needing keys (), table rows/cells (avoid invalid HTML), avoiding CSS flexbox/grid layout issues from wrapper divs. Benefits: cleaner DOM, avoid styling issues from wrappers, semantic HTML, better accessibility. Key syntax: <React.Fragment key={id}> (shorthand <> doesn't support keys). Fragments are zero-cost abstractions - compiled away, no performance impact. Use liberally to avoid unnecessary DOM nesting.

Sources
99% confidence
A

React.memo is higher-order component for memoization. Prevents re-renders when props unchanged (shallow comparison). Usage: const MemoizedComponent = React.memo(Component). Custom comparison: React.memo(Component, (prevProps, nextProps) => /* return true if equal */). Only re-renders if props change. Use for: expensive render components (>50ms), frequently re-rendered leaf components with same props. Don't use everywhere - has comparison cost. Combine with useCallback/useMemo for prop stability (functions/objects). Profile with React DevTools Profiler before optimizing. Note: React Compiler (React 19+) auto-memoizes components, reducing manual React.memo needs. Class equivalent: PureComponent.

99% confidence
A

Error Boundaries catch JavaScript errors in child component tree, log errors, display fallback UI. Class implementation: componentDidCatch(error, info) and static getDerivedStateFromError(error). No native function component equivalent yet. Catches: render errors, lifecycle methods, constructors. Doesn't catch: event handlers (use try/catch), async code, SSR errors, errors in boundary itself. 2025 best practice: use react-error-boundary library (npm install react-error-boundary) for function components with useErrorBoundary hook. Example: . Hook lets you pass errors from event handlers/async code to nearest boundary. Essential for production resilience.

99% confidence
A

Code splitting loads components on-demand, reducing initial bundle size. React.lazy + Suspense: const Component = React.lazy(() => import('./Component')). Wrap with Suspense: <Suspense fallback={}>. Only works with default exports (or use export { Component as default }). Route-based splitting most impactful: lazy load routes with React Router/Next.js. Modern bundlers (Vite, Turbopack, Webpack 5) handle automatic chunking. Benefits: faster Time-to-Interactive, better Core Web Vitals. React 19 enhances Suspense with better streaming, asset loading coordination. Use for: routes (highest impact), modals/dialogs, tabs, admin panels, rarely-used features. Measure with Lighthouse/WebPageTest.

99% confidence
A

Custom hooks extract component logic into reusable functions. Naming: must start with 'use' (linter enforces). Can call other hooks. Example: function useLocalStorage(key: string, initial: T) { const [value, setValue] = useState(() => JSON.parse(localStorage.getItem(key) || JSON.stringify(initial))); useEffect(() => localStorage.setItem(key, JSON.stringify(value)), [key, value]); return [value, setValue] as const; }. Benefits: logic reuse across components, cleaner components, testable in isolation, composable. Share stateful logic, not state itself (each component gets own state). Follow hook rules (top-level, React functions only). Popular libraries: usehooks-ts, react-use. TypeScript highly recommended.

99% confidence
A

JSX is syntax extension for JavaScript that looks like HTML. JSX elements are transformed to JavaScript by Babel/TypeScript. Modern transform (React 17+): automatic JSX runtime, no need to import React. Old: React.createElement('div', null, 'Hello'). New: _jsx('div', { children: 'Hello' }). Expressions in {}: {variable}, {fn()}, {condition ? a : b}, {array.map()}. JSX prevents XSS attacks (auto-escapes values). Closer to JavaScript than HTML: className not class, htmlFor not for, camelCase event handlers (onClick), style={{}} object, self-closing tags required. JSX is optional but industry standard. TypeScript provides excellent JSX type checking.

99% confidence
A

Both are base classes for class components (legacy pattern). Component: re-renders when setState called or parent re-renders, no optimization. PureComponent: implements shouldComponentUpdate with shallow prop/state comparison, skips re-render if unchanged - equivalent to React.memo for classes. PureComponent has comparison cost but saves render cost. Pitfall: shallow comparison misses nested object changes (must use immutable updates). 2025 best practice: migrate to function components with hooks. Use React.memo instead of PureComponent, useState instead of setState, useEffect instead of lifecycle methods. Class components still supported but not recommended for new code. Legacy codebases can migrate incrementally.

99% confidence
A

is development-only tool highlighting potential problems. No production overhead (completely stripped). Enables: (1) Identifies unsafe lifecycles, (2) Warns about legacy string refs and findDOMNode, (3) Detects unexpected side effects via double-invocation (components, effects, state initializers), (4) Warns about deprecated APIs. React 18+: double-renders components and double-runs effects in dev to catch missing cleanup and non-idempotent code. React 19: enhanced checks for Server Components, async rendering issues. Wrap app: . Essential for production-ready code. If third-party library breaks, report issue or wrap only your code.

99% confidence
A

Portals render children into DOM node outside parent component hierarchy while preserving React tree position. Use ReactDOM.createPortal(children, domNode, key?). Common use cases: modals/dialogs, tooltips, popovers, dropdowns, notifications - elements that need to escape parent's overflow:hidden, z-index stacking, or CSS containment. Example: createPortal({children}, document.body). Events bubble through React tree (not DOM tree), context works normally, state/props flow naturally. Accessibility: manage focus trap, ARIA, ESC key handling. Modern alternative: CSS dialog element with showModal(). Portals essential for overlay UI avoiding CSS layout constraints and ensuring proper layering.

Sources
99% confidence
A

Concurrent rendering allows React to interrupt rendering, prioritize updates, work on multiple state versions simultaneously. React 18 features: automatic batching (all updates batched, even in promises/timeouts), transitions (useTransition/startTransition for non-urgent updates), Suspense for data fetching, useDeferredValue for deprioritizing expensive renders. Benefits: UI stays responsive during expensive operations, prioritize urgent updates (typing) over expensive (search results), smoother animations, better perceived performance. Opt-in: use createRoot() instead of ReactDOM.render(). React 19 enhances with full Server Components support, better streaming SSR, improved Suspense coordination. Backwards compatible - concurrent features opt-in. Fundamental shift enabling responsive UIs at scale.

99% confidence
A

Client-Side Rendering (CSR): React runs in browser, JavaScript builds UI, slower Time-to-Interactive, SEO challenges (crawlable but not optimal), full client-side control. Server-Side Rendering (SSR): React renders HTML on server, faster First Contentful Paint, better SEO/crawlability, requires hydration (client takes over). Static Site Generation (SSG): pre-render at build time, fastest option, limited dynamic data. React Server Components (RSC, React 19): server-only components with zero client JS, async/await in components, direct database access, seamless client/server composition. 2025 best practice: Next.js App Router (RSC by default) or Remix for full-stack apps. RSC reduces bundle size 40%+, improves TTI by 340ms. Hybrid approach: RSC for static content, client components ('use client') for interactivity.

99% confidence
A

Refs store values that persist across renders without triggering re-renders. Use refs for: (1) DOM manipulation - focus(), scrollIntoView(), play/pause video, measuring elements, (2) Storing mutable values - timer IDs, intervals, previous values, request IDs, (3) Third-party integration - Canvas, D3, maps, non-React widgets. Use state for: data that affects what renders, UI state, form inputs, toggles, counters. Key difference: changing ref.current doesn't re-render, changing state does. Don't read/write ref.current during render - only in effects/event handlers. Callback refs for dynamic elements: <div ref={node => node && measure(node)}>. Prefer declarative React patterns over imperative refs when possible.

99% confidence
A

React uses SyntheticEvent wrapper for cross-browser compatibility and consistent behavior. Attach handlers via camelCase props: onClick={handleClick}, onChange={handleChange}, onMouseOver={handleMouseOver}. SyntheticEvent provides same interface across browsers with stopPropagation() and preventDefault() methods. Event pooling removed in React 17+ for better performance. In function components, event handlers are automatically bound to component instance. Use arrow functions or useCallback to optimize performance. Events bubble up through component hierarchy by default. SyntheticEvent includes nativeEvent property for browser-specific access.

99% confidence
A

React implements event delegation by attaching one event listener per event type at the container level (root in React 17+, document in earlier versions), not individual elements. When event fires, React uses event bubbling to determine which component triggered it and calls appropriate handler. Benefits: reduced memory usage, faster initial render, easier cleanup. Critical for lists with many items - 1000 items with click handlers use 1 listener instead of 1000. Works with dynamic content - new elements automatically get event handling. Capture phase available via onClickCapture prop. Essential for React's performance with large applications.

99% confidence

General

1 question
A

useEffectEvent is a React Hook (stable in React 19.2) that extracts non-reactive logic from Effects into reusable functions called Effect Events. It solves the stale closure problem by always accessing the latest props and state values when invoked, without causing the Effect to re-run when those values change.

Syntax: const onSomething = useEffectEvent(callback) where callback is a function containing your Effect Event logic.

Key usage rules:

  1. Only call Effect Events inside useEffect, useLayoutEffect, or useInsertionEffect
  2. Never declare Effect Events in the dependency array (React's linter correctly ignores them)
  3. Define Effect Events in the same component/Hook as their Effect - don't pass to other components
  4. Use for logic that is conceptually an 'event' fired from an Effect (not user events)

When to use: Extract logic that needs the latest props/state without making the Effect reactive to those values (e.g., logging with current cart count when URL changes, without re-running on cart updates).

When NOT to use: Don't use it just to avoid specifying dependencies - this hides bugs. Only use for genuinely non-reactive event-like logic.

Migration: Upgrade to eslint-plugin-react-hooks@latest to prevent the linter from incorrectly suggesting Effect Events as dependencies.

Available in: React 19.2+ (transitioned from experimental to stable).

98% confidence