Interview Preparation

Practice real interview questions with detailed answers

97 Questions
Easy 22 questions
REACT.JS #1.1
Q1: What is React.js?
Ans: React is an open-source JavaScript library developed by Facebook (Meta) for building user interfaces, particularly single-page applications, using a component-based architecture and a virtual DOM for efficient rendering.
REACT.JS #1.2
Q2: Is React a framework or a library?
Ans: React is a library focused specifically on the view layer of an application; unlike a full framework, it does not prescribe routing, state management, or HTTP handling out of the box, though these can be added via companion libraries like React Router or Redux.
REACT.JS #1.3
Q3: What is JSX?
Ans: JSX (JavaScript XML) is a syntax extension for JavaScript that lets you write HTML-like markup directly within JavaScript code, which is then transpiled (typically by Babel) into React.createElement() calls.
Code Example
const element = <h1>Hello, world!</h1>;
// compiles to:
const element = React.createElement('h1', null, 'Hello, world!');
REACT.JS #1.4
Q4: Why do we use className instead of class in JSX?
Ans: class is a reserved keyword in JavaScript, so JSX uses className to set the CSS class attribute on an element, which React then maps to the DOM's class attribute.
Code Example
<div className="container">Content</div>
REACT.JS #1.5
Q5: What is the Virtual DOM?
Ans: The Virtual DOM is an in-memory, lightweight representation of the real DOM as a tree of JavaScript objects; React uses it to compute the minimal set of changes needed and batches updates to the real DOM for better performance.
REACT.JS #1.6
Q6: What is the difference between a React element and a React component?
Ans: An element is a plain, immutable JavaScript object describing what should appear on screen (created via JSX or React.createElement), while a component is a function or class that returns elements, encapsulating logic and can accept props.
REACT.JS #1.7
Q7: What is the difference between functional and class components?
Ans: Functional components are plain JavaScript functions that return JSX and use Hooks for state and lifecycle behavior, while class components extend React.Component, use this.state, and implement lifecycle methods; functional components with Hooks are now the recommended approach.
Code Example
function Greeting() {
  return <h1>Hello</h1>;
}
class Greeting extends React.Component {
  render() {
    return <h1>Hello</h1>;
  }
}
REACT.JS #1.8
Q8: What are props in React?
Ans: Props (short for properties) are read-only inputs passed from a parent component to a child component, used to configure and customize how the child renders and behaves.
Code Example
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
<Welcome name="Sara" />
REACT.JS #1.9
Q9: What is state in React?
Ans: State is data that is local to a component and can change over time; unlike props, state is managed within the component itself and triggers a re-render whenever it is updated.
REACT.JS #1.10
Q10: What is the difference between props and state?
Ans: Props are passed in from a parent and are read-only within the receiving component, while state is owned and managed internally by the component and can be updated using setState or a state-updater function.
REACT.JS #1.11
Q11: What is the useState Hook?
Ans: useState is a Hook that lets functional components hold local state; it returns a stateful value and a function to update it, and calling the updater re-renders the component with the new value.
Code Example
const [count, setCount] = useState(0);
setCount(count + 1);
REACT.JS #1.12
Q12: What are controlled components?
Ans: A controlled component is a form element (like an input) whose value is driven by React state, with changes handled through an onChange handler that updates the state, making React the single source of truth.
Code Example
<input value={name} onChange={(e) => setName(e.target.value)} />
REACT.JS #1.13
Q13: What is conditional rendering in React?
Ans: Conditional rendering means displaying different UI depending on certain conditions, typically implemented with JavaScript operators like ternaries, logical &&, or early returns within JSX.
Code Example
{isLoggedIn ? <Dashboard /> : <Login />}
{hasError && <ErrorMessage />}
REACT.JS #1.14
Q14: What are React Fragments?
Ans: Fragments ( or the shorthand <>) let you group a list of children without adding an extra node to the DOM, useful when a component must return multiple elements without a wrapping div.
Code Example
return (
  <>
    <td>Hello</td>
    <td>World</td>
  </>
);
REACT.JS #1.15
Q15: What is React Router used for?
Ans: React Router is the most widely used routing library for React, enabling client-side navigation between different views/components based on the URL without triggering a full page reload.
Code Example
<Routes>
  <Route path="/" element={<Home />} />
  <Route path="/about" element={<About />} />
</Routes>
REACT.JS #1.16
Q16: What are React DevTools and what are they used for?
Ans: React DevTools is a browser extension that lets you inspect the React component tree, view and edit props/state in real time, and profile component render performance to find unnecessary re-renders.
REACT.JS #1.17
Q17: What is the significance of children prop in React?
Ans: props.children is a special prop that contains whatever is nested between a component's opening and closing tags, allowing components to be composed and to wrap arbitrary content passed by their parent.
Code Example
function Card({ children }) {
  return <div className="card">{children}</div>;
}
<Card><p>Hello</p></Card>
REACT.JS #1.18
Q18: How does event handling differ in React compared to plain HTML/DOM?
Ans: In React, event handlers are passed as camelCase props (like onClick) referencing functions rather than strings, and React attaches a single listener at the root and uses event delegation internally instead of attaching a listener to every DOM node.
Code Example
<button onClick={() => alert('Clicked')}>Click</button>
REACT.JS #1.19
Q19: What is the significance of e.preventDefault() in React event handlers?
Ans: Calling e.preventDefault() inside a React event handler prevents the browser's default behavior for that event, such as stopping a form's default page-reload submission, just as it does with native DOM events.
Code Example
const handleSubmit = e => {
  e.preventDefault();
  submitForm();
};
REACT.JS #1.20
Q20: What are Prop Types and why use them?
Ans: PropTypes is a runtime type-checking library for React props, letting developers document and validate the expected type and shape of props during development, producing console warnings when a mismatch occurs (largely superseded by TypeScript in modern codebases).
Code Example
MyComponent.propTypes = {
  name: PropTypes.string.isRequired,
};
REACT.JS #1.21
Q21: What is the significance of the key error 'Each child in a list should have a unique key prop'?
Ans: This warning appears when rendering an array of elements without a key prop, which React needs to efficiently track identity across re-renders; while the app will typically still function, missing keys can lead to subtle bugs when the list changes.
REACT.JS #1.22
Q22: How do you update an object in state immutably?
Ans: You create a new object using the spread operator (or Object.assign) that copies existing properties and overrides the ones that changed, rather than mutating the original object directly.
Code Example
setUser(prev => ({ ...prev, name: 'New Name' }));
Medium 57 questions
REACT.JS #2.1
Q1: How does React's reconciliation algorithm work?
Ans: Reconciliation is the process React uses to diff the new virtual DOM tree against the previous one; it compares elements by type and position, reuses existing DOM nodes where possible, and uses keys to efficiently match items in lists.
REACT.JS #2.2
Q2: What is the useEffect Hook?
Ans: useEffect lets functional components perform side effects, such as data fetching, subscriptions, or manually changing the DOM, after render; it can also return a cleanup function that runs before the next effect or on unmount.
Code Example
useEffect(() => {
  document.title = `Count: ${count}`;
  return () => console.log('cleanup');
}, [count]);
REACT.JS #2.3
Q3: What is the dependency array in useEffect?
Ans: The dependency array is the second argument to useEffect that tells React when to re-run the effect; an empty array runs the effect only once after the initial render, omitting it runs the effect after every render, and listing values re-runs it only when those values change.
Code Example
useEffect(() => { fetchData(); }, [userId]);
REACT.JS #2.4
Q4: What is the useContext Hook?
Ans: useContext lets a component subscribe to a React Context and read its current value without wrapping the component in a Context.Consumer, simplifying prop drilling across deeply nested components.
Code Example
const theme = useContext(ThemeContext);
REACT.JS #2.5
Q5: What is the useRef Hook?
Ans: useRef returns a mutable ref object whose .current property persists across renders without causing a re-render when changed; it's commonly used to access DOM nodes directly or store mutable values.
Code Example
const inputRef = useRef(null);
<input ref={inputRef} />
inputRef.current.focus();
REACT.JS #2.6
Q6: What is the difference between useRef and useState?
Ans: Updating state with useState triggers a re-render and the new value is available only after re-render, whereas updating a useRef value does not trigger a re-render and the change is reflected immediately on .current.
REACT.JS #2.7
Q7: What is the useMemo Hook?
Ans: useMemo memoizes the result of an expensive computation and only recalculates it when one of its dependencies changes, helping avoid unnecessary recalculations on every render.
Code Example
const sorted = useMemo(() => sortItems(items), [items]);
REACT.JS #2.8
Q8: What is the useCallback Hook?
Ans: useCallback returns a memoized version of a callback function that only changes if one of its dependencies changes, which is useful for preventing unnecessary re-renders of child components that rely on reference equality.
Code Example
const handleClick = useCallback(() => doSomething(id), [id]);
REACT.JS #2.9
Q9: What is the difference between useMemo and useCallback?
Ans: useMemo memoizes and returns the value of a computation, while useCallback memoizes and returns the function itself; useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).
REACT.JS #2.10
Q10: What is the useReducer Hook?
Ans: useReducer is an alternative to useState for managing complex state logic; it accepts a reducer function and an initial state, returning the current state and a dispatch function, similar to Redux's pattern.
Code Example
const [state, dispatch] = useReducer(reducer, initialState);
dispatch({ type: 'increment' });
REACT.JS #2.11
Q11: When should you use useReducer instead of useState?
Ans: useReducer is preferable when state logic is complex, involves multiple sub-values, or the next state depends on the previous one in non-trivial ways, since it centralizes update logic in a single reducer function.
REACT.JS #2.12
Q12: What are custom Hooks?
Ans: A custom Hook is a JavaScript function whose name starts with 'use' that can call other Hooks, allowing you to extract and reuse stateful logic across multiple components without duplicating code.
Code Example
function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);
  useEffect(() => {
    const handler = () => setWidth(window.innerWidth);
    window.addEventListener('resize', handler);
    return () => window.removeEventListener('resize', handler);
  }, []);
  return width;
}
REACT.JS #2.13
Q13: What are the rules of Hooks?
Ans: Hooks must only be called at the top level of a function component or custom Hook (never inside loops, conditions, or nested functions), and they must only be called from React function components or other custom Hooks.
REACT.JS #2.14
Q14: What is the Context API used for?
Ans: The Context API provides a way to share values like themes, authenticated user data, or locale across a component tree without having to pass props down manually at every level (avoiding 'prop drilling').
Code Example
const ThemeContext = React.createContext('light');
<ThemeContext.Provider value="dark">
  <App />
</ThemeContext.Provider>
REACT.JS #2.15
Q15: What is prop drilling and how can it be avoided?
Ans: Prop drilling is passing data through multiple layers of intermediate components that don't need it themselves, just to reach a deeply nested child; it can be avoided using the Context API, or state management libraries like Redux or Zustand.
REACT.JS #2.16
Q16: What are uncontrolled components?
Ans: An uncontrolled component manages its own state internally in the DOM, and React accesses its current value on demand using a ref rather than tracking every keystroke via state.
Code Example
const inputRef = useRef();
<input ref={inputRef} defaultValue="hello" />
REACT.JS #2.17
Q17: What is the significance of keys in React lists?
Ans: Keys are special string attributes that help React identify which items in a list have changed, been added, or removed, enabling efficient reordering and preventing unnecessary re-renders; keys should be stable and unique, not array indices when the list can change.
Code Example
{items.map(item => <li key={item.id}>{item.name}</li>)}
REACT.JS #2.18
Q18: Why is using array index as a key considered an anti-pattern?
Ans: Using the index as a key can cause incorrect component state association and rendering bugs when items are reordered, inserted, or removed, because React matches elements by key rather than by content, leading to stale UI or lost input state.
REACT.JS #2.19
Q19: What is the difference between React.PureComponent and React.Component?
Ans: React.PureComponent implements shouldComponentUpdate() with a shallow comparison of props and state automatically, skipping re-renders when nothing shallowly changed, while React.Component re-renders on every state or prop change unless you implement shouldComponentUpdate yourself.
REACT.JS #2.20
Q20: What is React.memo()?
Ans: React.memo() is a higher-order component that memoizes a functional component, skipping re-rendering when its props haven't changed (using a shallow comparison by default), analogous to PureComponent for function components.
Code Example
const MyComponent = React.memo(function MyComponent(props) {
  return <div>{props.value}</div>;
});
REACT.JS #2.21
Q21: What are Higher-Order Components (HOCs)?
Ans: A Higher-Order Component is a function that takes a component and returns a new component with additional props or behavior, used to share reusable logic like authentication checks or data fetching across multiple components.
Code Example
function withLogging(WrappedComponent) {
  return function(props) {
    console.log('rendering', WrappedComponent.name);
    return <WrappedComponent {...props} />;
  };
}
REACT.JS #2.22
Q22: What is the render props pattern?
Ans: The render props pattern is a technique for sharing code between components using a prop whose value is a function that returns JSX, allowing the parent to control what gets rendered based on the child's internal state.
Code Example
<DataProvider render={data => <Display data={data} />} />
REACT.JS #2.23
Q23: What are React Error Boundaries?
Ans: Error boundaries are class components that implement componentDidCatch() and/or static getDerivedStateFromError() to catch JavaScript errors anywhere in their child component tree, log them, and display a fallback UI instead of crashing the whole app.
Code Example
class ErrorBoundary extends React.Component {
  state = { hasError: false };
  static getDerivedStateFromError() { return { hasError: true }; }
  render() {
    return this.state.hasError ? <h1>Something went wrong.</h1> : this.props.children;
  }
}
REACT.JS #2.24
Q24: Can functional components act as error boundaries?
Ans: No, error boundaries currently must be class components, since there is no Hook equivalent for componentDidCatch or getDerivedStateFromError; libraries like react-error-boundary provide a functional wrapper around a class-based implementation.
REACT.JS #2.25
Q25: What are React Portals?
Ans: Portals provide a way to render children into a DOM node that exists outside the parent component's DOM hierarchy, useful for modals, tooltips, and dropdowns that need to escape overflow or z-index constraints of their parent.
Code Example
ReactDOM.createPortal(<Modal />, document.getElementById('modal-root'));
REACT.JS #2.26
Q26: What is forwardRef used for?
Ans: forwardRef lets a component pass a ref it receives through to a child DOM node or component, enabling parent components to directly access a child's underlying DOM element, commonly used when building reusable component libraries.
Code Example
const FancyInput = React.forwardRef((props, ref) => (
  <input ref={ref} className="fancy" {...props} />
));
REACT.JS #2.27
Q27: What is React.lazy() used for?
Ans: React.lazy() lets you dynamically import a component and code-split it so it's only loaded when actually rendered, reducing the initial bundle size; it must be paired with a Suspense component to show a fallback while loading.
Code Example
const OtherComponent = React.lazy(() => import('./OtherComponent'));
REACT.JS #2.28
Q28: What is the Suspense component used for?
Ans: Suspense lets you specify a loading indicator (fallback) for a part of the component tree that isn't ready to render yet, commonly used with React.lazy() for code-splitting and with data-fetching libraries that support Suspense.
Code Example
<Suspense fallback={<Spinner />}>
  <OtherComponent />
</Suspense>
REACT.JS #2.29
Q29: What is code-splitting in React and why is it useful?
Ans: Code-splitting breaks a large JavaScript bundle into smaller chunks that are loaded on demand rather than all at once, reducing initial load time; in React this is commonly done with dynamic import() combined with React.lazy() and Suspense.
REACT.JS #2.30
Q30: What are the main lifecycle methods of a class component?
Ans: The main lifecycle methods are componentDidMount() (runs after the component is first rendered), componentDidUpdate() (runs after updates), and componentWillUnmount() (runs right before the component is removed), alongside the render() method itself.
REACT.JS #2.31
Q31: How do Hooks replicate lifecycle methods like componentDidMount and componentWillUnmount?
Ans: useEffect with an empty dependency array behaves like componentDidMount, running once after the initial render, and the function it returns behaves like componentWillUnmount, running when the component unmounts.
Code Example
useEffect(() => {
  console.log('mounted');
  return () => console.log('unmounted');
}, []);
REACT.JS #2.32
Q32: What is the purpose of componentDidCatch?
Ans: componentDidCatch() is a lifecycle method used in error boundaries that is invoked after a descendant component throws an error, allowing you to log the error and update state to render a fallback UI.
REACT.JS #2.33
Q33: What is shouldComponentUpdate used for?
Ans: shouldComponentUpdate() lets a class component control whether it re-renders in response to a change in props or state, returning false skips the re-render, which is a manual way to optimize performance before React.memo/PureComponent existed.
REACT.JS #2.34
Q34: What is the difference between state and lifecycle in class components vs Hooks?
Ans: Class components tie state to this.state and spread related logic across separate lifecycle methods, while Hooks let you colocate related state and side-effect logic together inside a function component, making related code easier to organize and reuse.
REACT.JS #2.35
Q35: What is React's StrictMode?
Ans: StrictMode is a development-only tool that helps surface potential problems by intentionally double-invoking certain functions (like component render, and some effects in React 18+), warning about deprecated APIs, and highlighting unsafe lifecycle usage; it renders no visible UI itself.
Code Example
<React.StrictMode>
  <App />
</React.StrictMode>
REACT.JS #2.36
Q36: What is server-side rendering (SSR) and why use it with React?
Ans: SSR renders React components to HTML on the server and sends that markup to the browser, improving perceived load time and SEO by giving users and crawlers meaningful content before JavaScript finishes loading and hydrating.
REACT.JS #2.37
Q37: What is the difference between client-side rendering and server-side rendering?
Ans: Client-side rendering ships a minimal HTML shell and lets the browser download and execute JavaScript to build the UI, while server-side rendering generates the full HTML on the server per request, resulting in faster first paint but requiring hydration on the client.
REACT.JS #2.38
Q38: How do you pass data between sibling components in React?
Ans: Since data flows down through props, sibling components typically share data by lifting shared state up to their closest common ancestor, which then passes the state and updater functions down to both siblings as props.
REACT.JS #2.39
Q39: What is 'lifting state up' in React?
Ans: Lifting state up means moving shared state to the closest common ancestor of the components that need it, so that data flows down as props and stays synchronized between siblings instead of duplicating state in each component.
REACT.JS #2.40
Q40: What is Redux and how does it relate to React?
Ans: Redux is a predictable state management library that stores an application's entire state in a single, centralized store, updated only via dispatched actions processed by pure reducer functions; react-redux provides bindings to connect React components to that store.
Code Example
const counterReducer = (state = 0, action) => {
  switch (action.type) {
    case 'increment': return state + 1;
    default: return state;
  }
};
REACT.JS #2.41
Q41: What is the difference between Redux and the Context API?
Ans: Context API is built into React and is best for passing relatively static or infrequently changing data through the tree, while Redux offers a structured, predictable pattern with middleware, dev tools, and better performance for complex, frequently updated global state.
REACT.JS #2.42
Q42: What are React Hooks rules regarding conditional calls?
Ans: Hooks must always be called in the same order on every render, so they cannot be placed inside if statements, loops, or nested functions; conditional logic should instead go inside the Hook itself (e.g., inside useEffect's callback).
REACT.JS #2.43
Q43: What is the significance of the dependency array being empty vs omitted in useEffect?
Ans: An empty array ([]) means the effect runs only once after mount and never again, while omitting the array entirely means the effect runs after every single render, which can lead to performance issues or infinite loops if not handled carefully.
REACT.JS #2.44
Q44: How do you optimize performance in a React application?
Ans: Common techniques include memoizing components with React.memo, memoizing values/functions with useMemo/useCallback, code-splitting with React.lazy, virtualizing long lists, avoiding unnecessary re-renders by keeping state as local as possible, and using the React DevTools Profiler to identify bottlenecks.
REACT.JS #2.45
Q45: How do you handle forms with multiple inputs in React?
Ans: A common pattern is to store all field values in a single state object and use a shared onChange handler that updates the corresponding key using the input's name attribute, often combined with computed property names.
Code Example
const [form, setForm] = useState({ name: '', email: '' });
const handleChange = e => setForm({ ...form, [e.target.name]: e.target.value });
REACT.JS #2.46
Q46: What is component composition and why is it preferred over inheritance in React?
Ans: Composition means building complex UIs by combining smaller components (often via props.children or render props) rather than extending a base component class; React's team recommends composition because it's more flexible and avoids the tight coupling and fragility of deep inheritance chains.
REACT.JS #2.47
Q47: How do you fetch data in a React component?
Ans: Data fetching is typically done inside a useEffect Hook that calls fetch() or a library like axios, storing the result in state; libraries like React Query or SWR are often used to handle caching, retries, and loading/error states more robustly.
Code Example
useEffect(() => {
  fetch('/api/users')
    .then(res => res.json())
    .then(data => setUsers(data));
}, []);
REACT.JS #2.48
Q48: What is React Query (TanStack Query) used for?
Ans: React Query is a data-fetching and caching library that manages server state in React apps, handling caching, background refetching, request deduplication, and loading/error states, reducing the need for manual useEffect-based fetching.
REACT.JS #2.49
Q49: What is the difference between client state and server state?
Ans: Client state is local UI state owned entirely by the app (like form input or a toggle), while server state is data that originates from and is owned by a remote server, which can become stale and requires syncing, caching, and revalidation.
REACT.JS #2.50
Q50: What are Synthetic Events in React?
Ans: SyntheticEvent is React's cross-browser wrapper around the browser's native event object, providing a consistent API across different browsers while still giving access to the underlying native event via e.nativeEvent.
Code Example
function handleClick(e) {
  console.log(e.type); // 'click'
}
REACT.JS #2.51
Q51: Why is TypeScript often used with React?
Ans: TypeScript adds static type-checking to React code, catching prop-type mismatches, incorrect Hook usage, and other bugs at compile time rather than runtime, and improves editor autocompletion and refactoring safety in larger codebases.
REACT.JS #2.52
Q52: What testing tools are commonly used with React?
Ans: Jest is the most common test runner and assertion library, often paired with React Testing Library, which encourages testing components by simulating user interactions and asserting on rendered output rather than internal implementation details.
Code Example
test('renders greeting', () => {
  render(<Greeting name="Sara" />);
  expect(screen.getByText('Hello, Sara')).toBeInTheDocument();
});
REACT.JS #2.53
Q53: What is the philosophy behind React Testing Library?
Ans: React Testing Library encourages writing tests that resemble how users interact with the application—querying by visible text, roles, or labels rather than component internals or class names—so tests remain resilient to refactoring.
REACT.JS #2.54
Q54: What is the difference between React 17 and React 18 regarding root rendering?
Ans: React 18 introduced createRoot() from react-dom/client to replace the legacy ReactDOM.render() API, enabling concurrent features; rendering with the old API opts an app out of React 18's concurrent rendering capabilities.
Code Example
import { createRoot } from 'react-dom/client';
const root = createRoot(document.getElementById('root'));
root.render(<App />);
REACT.JS #2.55
Q55: What are common React anti-patterns to avoid?
Ans: Common anti-patterns include mutating state directly instead of using the setter, using array indices as keys in dynamic lists, overusing Context for frequently-changing state, deeply nesting components unnecessarily, and putting too much logic directly inside JSX instead of extracting it.
REACT.JS #2.56
Q56: What is the significance of immutability in React state management?
Ans: React relies on reference equality checks to detect changes efficiently; mutating state objects or arrays in place means the reference stays the same, so React (and optimizations like PureComponent or memo) may fail to detect the change and skip a necessary re-render.
Code Example
// Wrong: state.push(newItem)
// Correct:
setItems([...items, newItem]);
REACT.JS #2.57
Q57: What is the significance of functional updates in useState?
Ans: Passing a function to the state setter (e.g., setCount(prev => prev + 1)) ensures the update is based on the most current state value, which is important when updating state multiple times in a row or inside closures that might reference stale state.
Code Example
setCount(prevCount => prevCount + 1);
Hard 18 questions
REACT.JS #3.1
Q1: What is the significance of the key prop when using Portals?
Ans: Keys behave the same for portals as for any other React element; even though a portal renders elsewhere in the DOM, it still participates in the normal React tree for event bubbling and reconciliation purposes, so keys remain relevant when rendering lists of portals.
REACT.JS #3.2
Q2: What is useImperativeHandle used for?
Ans: useImperativeHandle customizes the instance value that is exposed to parent components when using ref, letting you expose a limited, specific API instead of the raw DOM node.
Code Example
useImperativeHandle(ref, () => ({
  focus: () => inputRef.current.focus()
}));
REACT.JS #3.3
Q3: What is the significance of the useLayoutEffect Hook?
Ans: useLayoutEffect fires synchronously after all DOM mutations but before the browser paints, making it suitable for reading layout and synchronously re-rendering to avoid visual flicker, unlike useEffect which fires asynchronously after paint.
REACT.JS #3.4
Q4: What is the difference between synchronous and batched state updates in React?
Ans: React batches multiple state updates that occur within the same event handler into a single re-render for performance; React 18 extended automatic batching to updates inside promises, timeouts, and native event handlers, which previously were not batched.
REACT.JS #3.5
Q5: What is React 18's concurrent rendering?
Ans: Concurrent rendering allows React to prepare multiple versions of the UI at the same time, interrupt rendering work that is no longer relevant, and prioritize urgent updates over less urgent ones, improving perceived responsiveness without blocking the main thread.
REACT.JS #3.6
Q6: What is useTransition used for?
Ans: useTransition lets you mark certain state updates as non-urgent 'transitions,' so React can keep the UI responsive by rendering more urgent updates first and showing the transition's result when it's ready, along with an isPending flag to show a pending state.
Code Example
const [isPending, startTransition] = useTransition();
startTransition(() => setTab('profile'));
REACT.JS #3.7
Q7: What is useDeferredValue used for?
Ans: useDeferredValue lets you defer re-rendering a non-urgent part of the UI, returning a deferred version of a value that lags behind the latest value until more urgent updates have completed, useful for keeping typing responsive while filtering large lists.
Code Example
const deferredQuery = useDeferredValue(query);
REACT.JS #3.8
Q8: What is hydration in the context of React?
Ans: Hydration is the process by which React attaches event listeners and internal state to server-rendered HTML on the client, reusing the existing markup instead of re-creating the DOM from scratch, used with server-side rendering frameworks like Next.js.
REACT.JS #3.9
Q9: What is list virtualization and when should you use it?
Ans: List virtualization (or windowing) renders only the items currently visible in the viewport instead of the entire list, dramatically improving performance for very long lists; libraries like react-window and react-virtualized implement this pattern.
REACT.JS #3.10
Q10: What is the difference between React.Component and PureComponent regarding deep data structures?
Ans: Both perform shallow comparisons only, so mutating a nested object or array in place (rather than creating a new reference) will not be detected by PureComponent's shouldComponentUpdate, leading to a missed re-render; immutable update patterns are required.
REACT.JS #3.11
Q11: What is the difference between shallow rendering and full DOM rendering in testing?
Ans: Shallow rendering (via Enzyme) renders only one level deep, stubbing out child components, while full DOM rendering mounts the entire component tree into a real or simulated DOM; React Testing Library favors full rendering to better reflect actual behavior.
REACT.JS #3.12
Q12: What is the useId Hook used for?
Ans: useId (introduced in React 18) generates a unique, stable ID that is consistent between server and client renders, useful for associating form labels with inputs via id/htmlFor without risking hydration mismatches.
Code Example
const id = useId();
<label htmlFor={id}>Name</label>
<input id={id} />
REACT.JS #3.13
Q13: What is the useSyncExternalStore Hook used for?
Ans: useSyncExternalStore lets components safely subscribe to external data sources outside of React's state (like a browser API or a third-party store) in a way that's compatible with concurrent rendering, avoiding tearing between renders.
REACT.JS #3.14
Q14: What is 'tearing' in the context of concurrent React rendering?
Ans: Tearing refers to a UI inconsistency where different parts of the same render show different versions of external mutable state because React rendered concurrently while that state changed mid-render; hooks like useSyncExternalStore are designed to prevent it.
REACT.JS #3.15
Q15: What are React Server Components?
Ans: React Server Components are components that render entirely on the server, never shipping their JavaScript to the client, allowing direct access to server-side resources (like a database) and reducing client bundle size; they're used alongside regular client components, notably in Next.js's App Router.
REACT.JS #3.16
Q16: What is the difference between a React Server Component and a Client Component?
Ans: Server Components run only on the server and cannot use state, effects, or browser APIs, whereas Client Components (marked with 'use client') run in the browser, can use Hooks and event handlers, and are what traditional React components have always been.
REACT.JS #3.17
Q17: What is the significance of the 'use client' directive?
Ans: The 'use client' directive, used in frameworks supporting React Server Components like Next.js, marks a module boundary indicating that the component and its imports should be bundled and rendered on the client rather than the server.
REACT.JS #3.18
Q18: What is a stale closure in React and how does it happen?
Ans: A stale closure occurs when a function (like an effect or event handler) captures an outdated value of a state or prop variable from a previous render, often because it was defined without the current variable in its dependency array.