17 Jun 2026, 12:00 AM 30 min read

100+ React Interview Questions

100+ React Interview Questions

React Interview Questions and Answers

Preparing for a React interview can be daunting, but having access to the right questions can make all the difference. A prioritized list of 100+ questions and solutions has been created, covering essential topics like React fundamentals, React Hooks, React Router, internationalization in React, testing of React apps, and the latest React 19 features.

This comprehensive guide is designed to help you prepare effectively, boost your confidence, and ensure you make a strong impression during your interview.

What's new in the May 2026 update

  • 10 new questions covering React 19: Actions, useActionState, useOptimistic, the use hook, Server Components, the React Compiler, and form actions, in the "React 19 and modern React" section below.
  • Existing answers updated so function components and hooks are the default, and class-based patterns are flagged where they're now legacy.
  • All code samples checked against React 19.

If you're looking for more in-depth React interview preparation materials, also check out these resources:

  • React Interview Playbook
  • Practice React coding interview questions
  • Practice React quiz interview questions

React fundamentals

Mastering React fundamentals is crucial in front end interviews because most companies rely on React for building modern web applications, and interview questions often test your ability to reason about components, state management, and data flow. A solid grasp of these core concepts is an important step to achieving interview success.

1. What is React, and what are its main features?

React is a JavaScript library developed by Facebook for creating user interfaces, particularly in single-page applications. It enables the use of reusable components that manage their own state. Key advantages include a component-driven architecture, optimized updates through the virtual DOM, a declarative approach for better readability, and robust community backing.

2. What is JSX and how does it work?

JSX, short for JavaScript XML, is a syntax extension for JavaScript that allows you to write HTML-like code within JavaScript. It makes building React components easier. JSX gets converted into JavaScript function calls, often by Babel. For instance,

<div>Hello, world!</div>
is transformed into
React.createElement('div', null, 'Hello, world!')
.

3. Explain the concept of the Virtual DOM in React.

The virtual DOM is a simplified version of the actual DOM used by React. It allows for efficient UI updates by comparing the virtual DOM to the real DOM and making only the necessary changes through a process known as reconciliation.

4. How does virtual DOM in React work? What are its benefits and downsides?

The virtual DOM in React is an in-memory representation of the real DOM. When state or props change, React creates a new virtual DOM tree, compares it to the previous one using a diffing algorithm, and efficiently updates only the parts of the real DOM that changed.

  • Benefits: It improves performance by reducing costly direct DOM manipulations and makes UI updates declarative and predictable.
  • Downsides: There's some overhead from diffing and extra memory usage, and in very dynamic UIs, it may not always outperform manual optimizations.

5. What is the difference Between React Node, React Element, and React Component?

A React Node refers to any unit that can be rendered in React, such as an element, string, number, or null. A React Element is an immutable object that defines what should be rendered, typically created using JSX or React.createElement. A React Component is either a function or class that returns React Elements, enabling the creation of reusable UI components.

6. What are React Fragments used for?

React Fragments allow you to group multiple elements without adding extra nodes to the DOM. They are particularly useful when you need to return multiple elements from a component but don't want to wrap them in a container element. You can utilize shorthand syntax

<>...</>
or React.Fragment.

return ( <> <ChildComponent1 /> <ChildComponent2 /> </>);

7. What is the purpose of the key prop in React?

In React, the key prop is used to uniquely identify elements in a list, allowing React to optimize rendering by updating and reordering items more efficiently. Without unique keys, React might re-render elements unnecessarily, causing performance problems and potential bugs.

{ items.map((item) => <ListItem key={item.id} value={item.value} />);}

8. What is the consequence of using array indices as keys in React?

Using array indices as keys can lead to performance issues and unexpected behavior, especially when reordering or deleting items. React relies on keys to identify elements uniquely, and using indices can cause components to be re-rendered unnecessarily or display incorrect data.

9. What are props in React? How are they different from state?

Props (short for properties) are inputs to React components that allow you to pass data from a parent component to a child component. They are immutable and are used to configure a component. In contrast, state is internal to a component and can change over time, typically due to user interactions or other events.

10. What is the difference between React's class components and functional components?

Class components are ES6 classes that extend React.Component and rely on lifecycle methods (componentDidMount, componentDidUpdate, etc.) and this.state. Function components are plain functions that take props as input and return JSX, and use hooks (useState, useEffect, useRef, etc.) for state and side effects. Since hooks landed in React 16.8, function components are the default for new code; class components are kept for backward compatibility and are no longer the recommended pattern.

11. When should you use a class component over a function component?

Default to function components. Class components are legacy: new APIs like Suspense data fetching, the use hook, Actions, Server Components, and the React Compiler are designed for function components only. The one remaining reason to write a class today is implementing an error boundary, which still requires static getDerivedStateFromError / componentDidCatch.

12. What is React Fiber?

React Fiber is a complete rewrite of the React core algorithm, designed to improve performance and enable new features like async rendering, error boundaries, and incremental rendering. It breaks down the rendering process into smaller chunks, allowing React to pause, abort, or prioritize updates as needed.

13. What is reconciliation?

Reconciliation is the process by which React updates the DOM to match the virtual DOM efficiently. It involves comparing the new virtual DOM tree with the previous one and determining the minimum number of changes required to update the actual DOM. This process ensures optimal performance by avoiding unnecessary re-renders.

14. What is the difference between Shadow DOM and Virtual DOM?

The Shadow DOM is a web standard that encapsulates a part of the DOM, isolating it from the rest of the document. It's used for creating reusable, self-contained components without affecting the global styles or scripts.

The Virtual DOM is an in-memory representation of the actual DOM used to optimize rendering. It compares the current and previous states of the UI, updating only the necessary parts of the DOM, which improves performance.

15. What is the difference between Controlled and Uncontrolled React components?

In controlled components, form data is managed through the component's state, making it the definitive source of truth. Input value changes are handled by event handlers. In uncontrolled components, the form state is managed internally and accessed via refs. Controlled components provide more control and are easier to test, while uncontrolled components are simpler for basic use cases.

Example of a controlled component:

function ControlledInput() { const [value, setValue] = React.useState(''); return ( <input type="text" value={value} onChange={(e) => setValue(e.target.value)} /> );}

Example of an uncontrolled component:

function UncontrolledInput() { const inputRef = React.useRef(); return <input type="text" ref={inputRef} />;}

16. How would you lift the state up in a React application, and why is it necessary?

Lifting state up in React involves moving the state from child components to their nearest common ancestor. This pattern is used to share state between components that don't have a direct parent-child relationship. By lifting state up, you can avoid prop drilling and simplify the management of shared data.

const Parent = () => { const [counter, setCounter] = useState(0); return ( <div> <Child1 counter={counter} /> <Child2 setCounter={setCounter} /> </div> );}; const Child1 = ({ counter }) => <h1>{counter}</h1>; const Child2 = ({ setCounter }) => ( <button onClick={() => setCounter((prev) => prev + 1)}>Increment</button> );

17. What are Pure Components?

Pure Components in React are components that only re-render when their props or state change. They use shallow comparison to check if the props or state have changed, preventing unnecessary re-renders and improving performance.

  • Class components can extend React.PureComponent to become pure
  • Functional components can use React.memo for the same effect
const PureFunctionalExample = React.memo(function ({ value }) { return <div>{value}</div>;});

With the React Compiler, manual memoization with React.memo, useMemo, and useCallback is rarely needed; the compiler inserts equivalent memoization automatically.

18. What is the difference between createElement and cloneElement?

The difference between createElement and cloneElement in React is as follows:

createElement:

  • Used to create a new React element.
  • It takes the type of the element (e.g., 'div', a React component), props, and children, and returns a new React element.
  • Commonly used internally by JSX or when dynamically creating elements. Example:
React.createElement('div', { className: 'container' }, 'Hello World');

cloneElement:

  • Used to clone an existing React element and optionally modify its props.
  • It allows you to clone a React element and pass new props or override the existing ones, keeping the original element's children and state.
  • Useful when you want to manipulate an element without recreating it. Example:
const element = <button className="btn">Click Me</button>; const clonedElement = React.cloneElement(element, { className: 'btn-primary' });

19. What is the role of PropTypes in React?

PropTypes was React's runtime prop type-checker. You declared expected types, and React would warn in the console when a mismatch occurred in development.

import PropTypes from 'prop-types'; function MyComponent({ name, age }) { return ( <div> {name} is {age} years old </div> );} MyComponent.propTypes = { name: PropTypes.string.isRequired, age: PropTypes.number.isRequired,};

PropTypes is deprecated as of React 19 and no longer ships from the react package. Use TypeScript instead — it catches the same mismatches at compile time and integrates with editor tooling.

20. What are stateless components?

Stateless components in React are components that do not manage or hold any internal state. They simply receive data via props and render UI based on that data. These components are often functional components and are used for presentational purposes.

Key points:

  • Do not use this.state
  • Render UI based on props
  • Focused on displaying information, not managing behavior
function StatelessComponent({ message }) { return <div>{message}</div>;}

Stateless components are simpler, easier to test, and often more reusable. With the introduction of hooks, React components are mostly written using functions and can contain state via the useState hook.

21. What are stateful components?

Stateful components in React are components that manage and hold their own internal state. They can modify their state in response to user interactions or other events and re-render themselves when the state changes.

Key points:

  • Use this.state (in class components) or useState (in functional components)
  • Can update state using event handlers or lifecycle methods
  • Handle logic and data management
function StatefulComponent() { const [count, setCount] = React.useState(0); return ( <div> <p>{count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> );}

Stateful components are essential for handling dynamic and interactive UIs.

22. What are the recommended ways for type checking of React component props?

Use TypeScript. It catches prop mismatches at compile time, integrates with editor tooling (autocomplete, refactors, jump-to-definition), and is the default in most React project templates.

type MyComponentProps = { name: string; age: number;}; function MyComponent({ name, age }: MyComponentProps) { return ( <div> {name} is {age} years old </div> );}

The older alternative was PropTypes, a runtime checker that warned in dev mode when prop types didn't match. It is deprecated as of React 19 and no longer ships from the react package. If you're maintaining a codebase that still uses prop-types, migrate to TypeScript.

23. Why does React recommend against mutating state?

React advises against mutating state as it can lead to unexpected behaviors and bugs. State immutability helps efficiently determine when components need re-rendering; direct mutations may prevent React from detecting changes.

React Hooks

Mastering React hooks is important in front end interviews because hooks are the standard way to manage state, side effects, and component lifecycle in modern React. Demonstrating a solid understanding of hooks shows you can write clean, functional components and solve complex problems without relying on outdated class patterns.

24. What are the benefits of using hooks in React?

Hooks enable the use of state and other React features in functional components, replacing the need for class components. They streamline code by reducing the reliance on lifecycle methods, enhance readability, and facilitate the reuse of stateful logic across components.

Popular hooks like useState and useEffect are used for managing state and side effects.

25. What are the rules of React hooks?

React hooks should be called at the top level of a function, not inside loops, conditions, or nested functions. They must only be used within React function components or custom hooks. These guidelines ensure proper state management and lifecycle behavior.

26. What is the difference between useEffect and useLayoutEffect in React?

useEffect and useLayoutEffect both handle side effects in React functional components but differ in when they run:

  • useEffect runs asynchronously after the DOM has rendered, making it suitable for tasks like data fetching or subscriptions.
  • useLayoutEffect runs synchronously after DOM updates but before the browser paints, ideal for tasks like measuring DOM elements or aligning the UI with the DOM. Example:
import React, { useEffect, useLayoutEffect, useRef } from 'react';
function Example() { 
  const ref = useRef();
  useEffect(() => { 
    console.log('useEffect: Runs after DOM paint'); 
  });
  useLayoutEffect(() => { 
    console.log('useLayoutEffect: Runs before DOM paint'); 
    console.log('Element width:', ref.current.offsetWidth); 
  });
  return <div ref={ref}>Hello</div>;
}

27. What does the dependency array of useEffect affect?

The dependency array of useEffect controls when the effect re-runs:

  • If it's empty, the effect runs only once after the initial render.
  • If it contains variables, the effect re-runs whenever any of those variables change.
  • If omitted, the effect runs after every render.

28. What is the useRef hook in React and when should it be used?

The useRef hook creates a mutable object that persists through renders, allowing direct access to DOM elements, storing mutable values without causing re-renders, and maintaining references to values.

For instance, useRef can be utilized to focus on an input element:

import React, { useRef, useEffect } from 'react';
function TextInputWithFocusButton() { 
  const inputEl = useRef(null); 
  useEffect(() => { 
    inputEl.current.focus(); 
  }, []); 
  return <input ref={inputEl} type="text" />;
}

29. What is the purpose of callback function argument format of setState() in React class components and when should it be used?

This applies to class components, which are no longer the recommended pattern. The function-component equivalent (the updater form of useState) is shown at the end.

The callback (updater) form of setState() ensures state updates are based on the most current state and props. This matters when the new state depends on the previous state, because React may batch multiple updates and the this.state you'd read directly could be stale.

this.setState((prevState, props) => ({ 
  counter: prevState.counter + props.increment,
}));

The function-component equivalent uses the updater form of useState:

const [counter, setCounter] = useState(0);
setCounter((prev) => prev + props.increment);

30. What is the useCallback hook in React and when should it be used?

The useCallback hook memoizes functions to prevent their recreation on every render. This is especially beneficial when passing callbacks to optimized child components that depend on reference equality to avoid unnecessary renders. Use it when a function is passed as a prop to a memoized child component.

const memoizedCallback = useCallback(() => { 
  doSomething(a, b);
}, [a, b]);

31. What is the useMemo hook in React and when should it be used?

The useMemo hook memoizes costly calculations, recomputing them only when dependencies change. This enhances performance by avoiding unnecessary recalculations. It should be used for computationally intensive functions that don't need to run on every render.

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

32. What is the useReducer hook in React and when should it be used?

The useReducer hook manages complex state logic in functional components, serving as an alternative to useState. It's ideal when state has multiple fields (and there are constraints around how they should be mutated), or when the next state relies on the previous one.

The useReducer hook accepts a reducer function + an initial state. The reducer function is passed the current state and action and returns a new state.

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

33. What is the useId hook in React and when should it be used?

The useId hook generates unique IDs for elements within a component, which is crucial for accessibility by dynamically creating ids that can be used for linking form inputs and labels. It guarantees unique IDs across the application even if the component renders multiple times.

import { useId } from 'react';
function MyComponent() { 
  const id = useId();
  return ( 
    <div> 
      <label htmlFor={id}>Name:</label> 
      <input id={id} type="text" /> 
    </div> 
  );
}

34. Can you explain how to create and use custom hooks in React?

To create and use custom hooks in React:

  1. Create a function that starts with use and uses built-in hooks like useState or useEffect
  2. Return the values or functions you want to share.

Example:

function useForm(initialState) { 
  const [formData, setFormData] = useState(initialState); 
  const handleChange = (e) => setFormData({ ...formData, [e.target.name]: e.target.value }); 
  return [formData, handleChange];
}

Use the Hook:

function MyForm() { 
  const [formData, handleChange] = useForm({ name: '', email: '' }); 
  return <input name="name" value={formData.name} onChange={handleChange} />;
}

Custom hooks let you reuse logic across components, keeping your code clean.

Advanced concepts

Mastering React's advanced concepts like Suspense, forwardRef(), and context demonstrates that you can handle performance optimization, code splitting, and complex component patterns. In interviews, this shows you're prepared to build scalable, maintainable applications beyond just basic component logic.

35. What does re-rendering mean in React?

In React, re-rendering refers to the process of updating the user interface (UI) in response to changes in the component's state or props. When the state or props of a component change, React re-renders the component to reflect the updated data in the UI.

This involves:

  1. Recalculating the JSX returned by the component
  2. Comparing the new JSX with the previous one (using the Virtual DOM)
  3. Updating the real DOM with only the differences (efficient rendering)
  4. Re-rendering ensures that the UI stays in sync with the component's state and props

36. What is forwardRef() in React used for?

Before React 19, function components didn't accept ref as a regular prop, so forwardRef() was used to pass a ref through to a child DOM element.

import React, { forwardRef } from 'react';
const MyComponent = forwardRef((props, ref) => <input ref={ref} {...props} />);

In React 19, ref is a regular prop on function components and forwardRef is deprecated. Destructure it from props:

function MyComponent({ ref, ...props }) { return <input ref={ref} {...props} />;}

37. What are error boundaries in React for?

Error boundaries catch JavaScript errors in their child components, log them, and display fallback UI instead of crashing the application. They utilize componentDidCatch and static getDerivedStateFromError methods but do not catch errors in event handlers or asynchronous code.

38. What is React Suspense?

React Suspense allows handling asynchronous operations more elegantly within components. It provides fallback content while waiting for resources like data or code to load. You can use it alongside React.lazy() for code splitting.

const LazyComponent = React.lazy(() => import('./LazyComponent'));
function MyComponent() { return ( 
  <React.Suspense fallback={<div>Loading...</div>}> 
    <LazyComponent /> 
  </React.Suspense> 
);}

39. Explain what React hydration is?

Hydration involves attaching event listeners and making server-rendered HTML interactive on the client side. After server-side rendering, React initializes dynamic behavior by attaching event handlers.

40. What are React Portals used for?

React Portals allow rendering children into a DOM node outside the parent component's hierarchy. This is useful for modals or tooltips that need to escape parent overflow or z-index constraints.

41. What is React strict mode and what are its benefits?

React Strict Mode is a development feature in React that activates extra checks and warnings to help identify potential issues in your app.

  • Detects unsafe lifecycles: Warns about deprecated lifecycle methods
  • Identifies side effects: Highlights components with side effects in render methods
  • Warns about unexpected state changes: Catches unexpected state mutations
  • Enforces best practices: Flags potential problems, encouraging modern practices
<React.StrictMode> <App /> </React.StrictMode>

Wrapping components in <React.StrictMode> activates these development checks without affecting production builds.

42. What is code splitting in a React application?

Code splitting enhances performance by dividing code into smaller chunks loaded on demand, thereby reducing initial load times. This can be achieved through dynamic import() statements or using React's React.lazy and Suspense.

const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() { return ( 
  <React.Suspense fallback={<div>Loading...</div>}> 
    <LazyComponent /> 
  </React.Suspense> 
);}

43. How would one optimize the performance of React contexts to reduce rerenders?

Optimizing context performance involves memoizing context values with useMemo, splitting contexts for isolated state changes, and employing selectors to rerender only necessary components.

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

44. What is the Flux pattern?

The Flux pattern manages application state through unidirectional data flow, simplifying debugging and enhancing maintainability with clear separation of concerns between Dispatcher, Stores, Actions, and Views.

45. Explain one-way data flow of React

In React, one-way data flow means data moves from parent to child components through props.

  • Parent to child: The parent passes data to the child
  • State updates: To change data, the child calls a function passed down by the parent

Example:

function Parent() { const [count, setCount] = React.useState(0); return <Child count={count} increment={() => setCount(count + 1)} />;}
function Child({ count, increment }) { return <button onClick={increment}>Count: {count}</button>;}

This ensures data flows in one direction, making the app more predictable.

46. What are some pitfalls of using context in React?

Context in React can lead to performance issues if not handled carefully, causing unnecessary re-renders of components that consume the context, even if only part of the context changes. Overusing context for state management can also make the code harder to maintain and understand. It's best to use context sparingly and consider other state management solutions like Redux or Zustand for more complex scenarios.

47. What are some React anti-patterns?

React anti-patterns are practices that can lead to inefficient or hard-to-maintain code. Common examples include:

  • Directly mutating state instead of using the state setter
  • Using useEffect to derive state from props (compute it during render instead)
  • Putting data into state that you can compute from other state or props
  • Not using keys in lists, or using the array index as a key for reorderable lists
  • Effects with missing or stale dependencies
  • Deeply nested state; prefer flat shapes with useReducer or a state library
  • Reading or writing refs during render (do it in effects or event handlers)
  • Using useState for values that don't drive rendering (use useRef instead)
  • Calling hooks conditionally or inside loops (breaks the Rules of Hooks)

The older class-component anti-patterns (using componentWillMount for data fetching or relying on componentWillReceiveProps) refer to APIs that were renamed to UNSAFE_* and no longer apply to function-component code.

48. How do you decide between using React state, context, and external state managers?

Choosing between React state, context, and external state managers depends on your application's complexity. Use React state for local component state, context for global state shared across multiple components, and external managers like Redux or MobX for complex state management requiring advanced features like optimizing re-renders.

49. Explain what happens when setState is called in React?

When setState is called in React:

  1. State update: It updates the component's state, triggering a re-render of the component
  2. Batching: React may batch multiple setState calls into a single update for performance optimization
  3. Re-render: React re-renders the component (and its child components if needed) with the new state
  4. Asynchronous: State updates may be asynchronous, meaning React doesn't immediately apply the state change; it schedules it for later to optimize performance

Example:

function Counter() { const [count, setCount] = React.useState(0);
 const increment = () => { setCount(count + 1); };
 return <button onClick={increment}>Count: {count}</button>;}

In this example, calling setState (via setCount) triggers a re-render with the updated count.

50. Explain prop drilling

Prop drilling is when you pass data from a parent component to a deeply nested child component through props, even if intermediate components don't use it.

Example:

function Grandparent() { const data = 'Hello from Grandparent'; return <Parent data={data} />;}
function Parent({ data }) { return <Child data={data} />;}
function Child({ data }) { return <p>{data}</p>;}

In this example, data is passed through multiple components, even though only the Child component uses it. Prop drilling is acceptable for small applications where the component hierarchy is shallow. When global state is needed to be accessed in deeper levels of the app, using context and/or external state managers might be better.

51. Describe lazy loading in React

Lazy loading in React is a technique where components are loaded only when they are needed, rather than at the initial page load. This helps reduce the initial load time and improve performance by splitting the code into smaller chunks.

Example:

import React, { Suspense, lazy } from 'react';
const LazyComponent = lazy(() => import('./LazyComponent'));
function App() { return ( 
  <Suspense fallback={<div>Loading...</div>}> 
    <LazyComponent /> 
  </Suspense> 
);}

In this example, LazyComponent is loaded only when it's rendered, and while loading, a fallback UI (Loading...) is displayed.

52. Discuss synthetic events in React

Synthetic events in React are a wrapper around native DOM events that ensure consistent behavior across browsers. They normalize the way events are handled, providing a unified API for React applications.

These events are wrapped in the SyntheticEvent object and expose the usual methods like preventDefault() and stopPropagation(). Since React 17, the root event listener is attached to the React root container (not document), which makes nested React trees work correctly together.

Example:

function MyComponent() { const handleClick = (event) => { event.preventDefault(); console.log('Button clicked'); };
 return <button onClick={handleClick}>Click me</button>;}

Older sources mention event pooling, where React reused the event object after the handler ran, which made the event unusable in async code. Event pooling was removed in React 17, so you can read or pass the event object asynchronously without calling event.persist().

53. Explain the React component lifecycle methods in class components.

Class lifecycle methods only apply to class components, which are no longer the recommended pattern. The function-component equivalents (using useEffect) are shown at the end.

React class components have lifecycle methods for different phases:

Mounting:

  • constructor: Initializes state or binds methods
  • componentDidMount: Runs after the component mounts, useful for API calls or subscriptions
componentDidMount() { console.log('Component mounted');}

Updating:

  • shouldComponentUpdate: Determines if the component should re-render
  • componentDidUpdate: Runs after updates, useful for side effects

Unmounting:

  • componentWillUnmount: Cleans up (e.g., removing event listeners).
componentWillUnmount() { console.log('Component will unmount');}

In function components, all of the above are expressed with useEffect:

useEffect( () => { console.log('Mounted or updated'); return () => { console.log('Will unmount'); }; }, [ ],);

54. What are concurrent features in React, and how do they improve rendering performance?

Concurrent features were introduced in React 18 (the experimental "Concurrent Mode" branding from React 17 is no longer used). They let React pause, interrupt, and resume rendering work instead of running it as a single blocking pass. This keeps the UI responsive: urgent updates like typing or clicks can preempt slower work like rendering a large list or filtering search results.

The features are opt-in via specific APIs (useTransition, useDeferredValue, and <Suspense> for data fetching), not a global mode switch.

55. How does React handle concurrent rendering with multiple updates and prioritize them?

React's scheduler assigns priority to updates based on how they're triggered. Updates from direct user interaction (click, input, focus) are treated as urgent and rendered synchronously. Updates wrapped in startTransition or read through useDeferredValue are non-urgent: React can interrupt them to handle a more urgent update, then resume. That's what allows a heavy filter or list render to coexist with typing into a search box without blocking it.

56. How would you handle long-running tasks or expensive computations in React applications without blocking the UI?

To avoid blocking the UI, use Web Workers, setTimeout, or requestIdleCallback for offloading heavy computations. Alternatively, break tasks into smaller parts and use React's Suspense or useMemo to only recompute when necessary.

Example using setTimeout for deferring computation:

const [data, setData] = useState(null);
useEffect(() => { setTimeout(() => { const result = computeExpensiveData(); setData(result); }, 0);}, []);

57. Explain server-side rendering of React applications and its benefits

Server-side rendering (SSR) involves rendering components on the server before sending fully rendered HTML to clients, improving initial load times and SEO through efficient hydration processes.

58. Explain static generation of React applications

Static generation pre-renders HTML at build time instead of runtime; this approach enhances performance by delivering static content quickly while improving SEO outcomes.

59. What are higher-order components in React?

Higher-order components (HOCs) are functions that take a component and return a new one with added props or behavior, facilitating logic reuse across components.

const withExtraProps = (WrappedComponent) => { return (props) => <WrappedComponent {...props} extraProp="value" />;};
const EnhancedComponent = withExtraProps(MyComponent);

HOCs were the dominant pattern for cross-cutting logic (auth, data fetching, theming) before hooks. Custom hooks cover almost all of those use cases now without the wrapper-component nesting. HOCs still appear in older codebases and some libraries (e.g., connect from react-redux), but new code should prefer a custom hook.

60. Explain the presentational vs container component pattern in React

The presentational vs container pattern split components into two roles: presentational components handled rendering (markup, styling) and received data via props, while container components handled state, data fetching, and behavior, then passed data down.

function UserListContainer() { const [users, setUsers] = useState([]); useEffect(() => { fetchUsers().then(setUsers); }, []); return <UserList users={users} />;}
function UserList({ users }) { return ( 
  <ul> 
    {users.map((u) => ( 
      <li key={u.id}>{u.name}</li> 
    ))} 
  </ul> 
);}

This pattern was popular before hooks; its original author (Dan Abramov) has since said it's no longer worth following as a hard rule. With hooks, the same separation is usually expressed by extracting a custom hook (e.g., useUsers()) rather than a wrapper component. New code typically blends the two roles into a single component plus a custom hook.

61. What are render props in React?

Render props in React allow code sharing between components through a prop that is a function. This function returns a React element, enabling data to be passed to child components.

function DataFetcher({ url, render }) { const [data, setData] = useState(null); useEffect(() => { fetch(url) .then((res) => res.json()) .then(setData); }, [url]); return render(data);}
<DataFetcher url="/api/data" render={(data) => <div>{data ? data.name : 'Loading...'}</div>}/>

Like HOCs, render props were a pre-hooks solution for sharing stateful logic. Most of those use cases are now solved with a custom hook (const data = useFetch(url)), which composes more naturally and avoids the render-prop pyramid. Render props are still useful in narrow cases where the consumer needs to control what to render based on parent-managed state (e.g., headless component libraries).

62. Explain the composition pattern in React.

The composition pattern in React involves building components by combining smaller, reusable ones instead of using inheritance. This encourages creating complex UIs by passing components as children or props.

function WelcomeDialog() { return ( 
  <Dialog> 
    <h1>Welcome</h1> 
    <p>Thank you for visiting our spacecraft!</p> 
  </Dialog> 
);}
function Dialog(props) { return <div className="dialog">{props.children}</div>;}

63. How do you re-render the view when the browser is resized?

To re-render the view on browser resize, use the useEffect hook to listen for the resize event and update state.

Example:

import React, { useState, useEffect } from 'react';
function ResizeComponent() { const [windowWidth, setWindowWidth] = useState(window.innerWidth);
 useEffect(() => { const handleResize = () => setWindowWidth(window.innerWidth); window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []);
 return <div>Window width: {windowWidth}px</div>;}
export default ResizeComponent;

This updates the state and re-renders the component whenever the window is resized.

64. How do you handle asynchronous data loading in React applications?

Asynchronous data loading uses useEffect alongside useState hooks; fetching data inside useEffect updates state with fetched results ensuring re-renders occur with new data.

import React, { useState, useEffect } from 'react';
const FetchAndDisplayData = () => { const [info, updateInfo] = useState(null); const [isLoading, toggleLoading] = useState(true);
 useEffect(() => { const retrieveData = async () => { try { const res = await fetch('https://api.example.com/data'); const data = await res.json(); updateInfo(data); } catch (err) { console.error('Error fetching data:', err); } finally { toggleLoading(false); } };
 retrieveData(); }, []);
 return ( 
   <div> 
     {isLoading ? ( 
       <p>Fetching data, please wait...</p> 
     ) : ( 
       <pre>{JSON.stringify(info, null, 2)}</pre> 
     )} 
   </div> 
 );};
export default FetchAndDisplayData;

65. What are some common pitfalls when doing data fetching in React?

Common pitfalls in data fetching with React include failing to handle loading and error states, neglecting to clean up subscriptions which can cause memory leaks, and improperly using lifecycle methods or hooks. Always ensure proper handling of these states, clean up after components, and utilize useEffect for side effects in functional components.

Let's Work Together

Ready to Grow Your
Business With Us?

Free consultation — tell us about your project and we'll get back within 1 hour.

500+ Projects Delivered
5★ Google Rating
Reply within 1 Hour
10+ Years Experience