DEV Community

Cover image for Basic React Interview Questions 🔥
SYED MD SAIFI HASSAN
SYED MD SAIFI HASSAN

Posted on

Basic React Interview Questions 🔥

1. What is React?

React is an open-source JavaScript library used for building user interfaces, particularly for single-page applications. It's developed and maintained by Facebook. React enables developers to create large web applications that can update and render efficiently in response to data changes without reloading the page.


2. Explain the difference between Real DOM and Virtual DOM?

  • Real DOM: Updates directly to the DOM tree and causes the entire page to re-render, which is slow and inefficient.
  • Virtual DOM: React uses a virtual DOM, which is a lightweight copy of the real DOM. It updates the virtual DOM first and then compares it with the previous version using a process called diffing. It then makes efficient updates to only the parts of the real DOM that changed.

3. What are the key features of React?

  • Declarative UI: Developers describe the UI state, and React manages the rendering.
  • Component-based architecture: UI is broken into reusable components.
  • Virtual DOM: For optimized rendering.
  • Unidirectional Data Flow: Data flows in one direction, making it predictable.
  • JSX: Syntax extension for JavaScript that lets you write HTML in JS.
  • React Hooks: Functions like useState and useEffect for managing state and lifecycle methods in functional components.

4. What is JSX?

JSX is a syntax extension that allows you to write HTML-like code inside JavaScript. It makes the code easier to understand and helps developers write React components more intuitively. Example:

const element = <h1>Hello, world!</h1>;
Enter fullscreen mode Exit fullscreen mode

5. Why can't browsers read JSX?

Browsers can only read plain JavaScript, not JSX. JSX is syntactic sugar for React.createElement calls, and needs to be transpiled into regular JavaScript using tools like Babel before the browser can understand it.


6. What are React components?

Components are the building blocks of a React application. They are reusable pieces of UI logic. Components can be class-based or functional:

  • Functional components: Use hooks to manage state and lifecycle.
  • Class components: Use lifecycle methods and this.state for managing state.

7. Differentiate between a Class component and a Functional component.

  • Class Component: Requires a render() method and manages state using this.state.

Example:

class MyComponent extends React.Component {
  render() {
    return <h1>Hello, World!</h1>;
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Functional Component: Uses hooks like useState and useEffect for state and side effects.

Example:

function MyComponent() {
  return <h1>Hello, World!</h1>;
}
Enter fullscreen mode Exit fullscreen mode

8. What is the difference between state and props in React?

  • State: Managed internally by the component. It is mutable and can be updated using setState (or useState in functional components).
  • Props: Passed from a parent component and are read-only. Used to pass data between components.

9. What are React hooks? Name some common hooks.

Hooks are functions that allow you to use React features (like state and lifecycle) in functional components. Common hooks:

  • useState: For managing state.
  • useEffect: For handling side effects like fetching data.
  • useContext: For consuming context values.

10. How do useState and useEffect work in React?

  • useState: Manages state in functional components.

Example:

const [count, setCount] = useState(0);
Enter fullscreen mode Exit fullscreen mode
  • useEffect: Used for side effects like data fetching, subscriptions, or manually updating the DOM.

Example:

useEffect(() => {
  // Runs after every render
}, []);
Enter fullscreen mode Exit fullscreen mode

11. What is the importance of key in React?

The key prop is crucial for React’s reconciliation process. When rendering a list of items, key helps React identify which items have changed, been added, or removed, making updates more efficient.


12. Explain the concept of lifting state up in React.

Lifting state up refers to moving state to a common ancestor component, allowing child components to share and access that state. This is useful when multiple components need to reflect or manipulate the same data.


13. How does one pass data between components in React?

  • Parent to Child: Via props.
  • Child to Parent: By passing a function as a prop and invoking it from the child component.
  • Between unrelated components: Via global state (e.g., Context API, Redux).

14. What are the new features introduced in React 18?

React 18 introduced:

  • Concurrent Rendering
  • Automatic Batching
  • useTransition hook
  • useDeferredValue hook
  • Improved Suspense for SSR

15. What is concurrent rendering in React 18?

Concurrent rendering in React 18 allows React to pause, interrupt, and resume rendering tasks to prioritize updates that result in a more responsive UI without blocking the main thread.


16. How does automatic batching work in React 18?

React 18 automatically batches multiple state updates together, even inside asynchronous functions like setTimeout. This optimizes rendering by combining state updates into one render instead of multiple.


17. What is the useTransition hook, and how does it work?

useTransition allows you to mark certain state updates as non-urgent, preventing UI from blocking during expensive renders. It provides a way to show fallback UI during transitions.


18. Explain the working of useDeferredValue in React 18.

useDeferredValue allows you to delay updates to parts of the UI without blocking other parts. It lets you defer re-rendering some components until a lower-priority render completes.


19. What is Suspense in React, and how does it work?

Suspense is a React component that allows you to show a fallback UI while waiting for asynchronous operations, like data fetching, to complete. Example:

<Suspense fallback={<div>Loading...</div>}>
  <MyComponent />
</Suspense>
Enter fullscreen mode Exit fullscreen mode

20. How has React 18 improved Suspense?

React 18 enhances Suspense by allowing it to work with server-side rendering (SSR) and data-fetching strategies.


21. What is the new startTransition function in React 18?

startTransition allows you to mark updates as non-urgent, ensuring that the UI remains responsive. It's typically used for actions that don’t require immediate feedback.


22. What is the difference between useTransition and startTransition?

  • useTransition: Hook-based API that provides a pending flag.
  • startTransition: Function-based API for non-urgent state updates.

23. How do you use the Concurrent Features introduced in React 18?

Concurrent features are automatically enabled by updating to React 18. You can use features like useTransition and Suspense to optimize the UI for responsiveness.


24. How does React 18 enhance server-side rendering (SSR)?

React 18 supports streaming SSR, allowing pages to start rendering in the browser before the server finishes rendering the whole page. This improves load times.


25. What is React Server Components, and how does it work with React 18?

React Server Components allow components to be rendered on the server, reducing the amount of JavaScript sent to the client and improving load times.


26. What role does the concurrentMode flag play in React 18?

In React 18, concurrent mode is now the default for features like transitions and automatic batching. You no longer need to enable it explicitly.


27. Explain the React lifecycle methods in detail.

Lifecycle methods are used in class components to run code at particular stages of a component’s life:

  • Mounting: componentDidMount()
  • Updating: componentDidUpdate()
  • Unmounting: componentWillUnmount()

28. What is React Context API, and when would you use it?

The Context API provides a way to pass data through the component tree without prop drilling. It's commonly used for global state, like theme or authentication status.


29. What are higher-order components (HOCs) in React?

HOCs are functions that take a component and return a new component with additional props or behavior.

Example:

const EnhancedComponent = higherOrderComponent(OriginalComponent);
Enter fullscreen mode Exit fullscreen mode

30. How does React handle forms and controlled components?

In controlled components, form data is handled by the component state. Each form element has a value prop linked to the component's state.


31. What are uncontrolled components in React?

Uncontrolled components manage their own state internally via the DOM. Refs are used to access form values.


32. What is Prop Drilling, and how can it be avoided?

Prop Drilling occurs when data is passed through multiple components unnecessarily. It can be avoided using Context API or state management libraries like Redux.


33. What are React Portals, and when should you use them?

Portals allow you to render a child component outside its parent DOM hierarchy. Useful for modals and tooltips that need to be rendered on top of everything else.


34. What are error boundaries in React?

Error boundaries catch JavaScript errors in a component tree and display a fallback UI instead of crashing the app. They are implemented using componentDidCatch and getDerivedStateFromError lifecycle methods.


35. What is Redux, and how does it work with React?

Redux is a state management library. It stores the application state in a single store and uses actions and reducers to update that state. React components can connect to Redux using the connect function or useSelector and useDispatch hooks.


36. Explain Redux Thunk.

Redux Thunk is a middleware that allows you to write action creators that return a function instead of an action. This function can dispatch actions asynchronously or conditionally, making it useful for handling side effects like API calls in Redux.

Example:

const fetchData = () => {
  return (dispatch) => {
    dispatch({ type: 'FETCH_DATA_REQUEST' });
    fetch('/api/data')
      .then(response => response.json())
      .then(data => dispatch({ type: 'FETCH_DATA_SUCCESS', payload: data }))
      .catch(error => dispatch({ type: 'FETCH_DATA_FAILURE', error }));
  };
};
Enter fullscreen mode Exit fullscreen mode

37. What is Redux Saga?

Redux Saga is another middleware library for managing side effects in Redux. Instead of returning functions, it uses generators to handle async actions in a more declarative style. Sagas listen for dispatched actions and perform tasks like API calls or data fetching.

Example:

function* fetchDataSaga() {
  try {
    const data = yield call(api.fetchData);
    yield put({ type: 'FETCH_DATA_SUCCESS', payload: data });
  } catch (error) {
    yield put({ type: 'FETCH_DATA_FAILURE', error });
  }
}
Enter fullscreen mode Exit fullscreen mode

38. What is the Context API in React?

The Context API provides a way to pass data through the component tree without having to pass props manually at every level. It is useful for sharing global data (like themes, authentication status) across components without prop drilling.

Example:

const MyContext = React.createContext();

const MyProvider = ({ children }) => {
  const [value, setValue] = useState("Hello");
  return <MyContext.Provider value={value}>{children}</MyContext.Provider>;
};
Enter fullscreen mode Exit fullscreen mode

39. What is prop drilling in React, and how do you avoid it?

Prop drilling refers to passing data from a parent to child component through multiple intermediate components. You can avoid it by using the Context API or state management libraries like Redux to store global state accessible by any component.


40. What is a PureComponent in React?

PureComponent is a React class component that implements shouldComponentUpdate with a shallow prop and state comparison. It prevents unnecessary re-renders when the props or state haven't changed.

Example:

class MyComponent extends React.PureComponent {
  render() {
    return <div>{this.props.value}</div>;
  }
Enter fullscreen mode Exit fullscreen mode

41. What is the difference between a controlled and uncontrolled component in React?

  • Controlled Component: State is fully controlled by React using useState or this.state.

Example:

<input type="text" value={value} onChange={(e) => setValue(e.target.value)} />
Enter fullscreen mode Exit fullscreen mode
  • Uncontrolled Component: The form element manages its own state internally, and the value is accessed using refs.

Example:

<input type="text" ref={inputRef} />
Enter fullscreen mode Exit fullscreen mode

42. What is the use of React Router?

React Router is a library for handling routing in React applications. It allows navigation between different components and pages without reloading the page, maintaining the single-page application behavior.

Example:

<BrowserRouter>
  <Route path="/" component={Home} /><Route path="/about" component={About} />
</BrowserRouter>
Enter fullscreen mode Exit fullscreen mode

43. What is lazy loading in React?

Lazy loading is a technique that delays loading components until they are needed, improving the performance of large applications. In React, you can use React.lazy and Suspense to load components lazily.

Example:

const LazyComponent = React.lazy(() => import("./LazyComponent"));

<Suspense fallback={<div>Loading...</div>}>
  <LazyComponent />
</Suspense>;
Enter fullscreen mode Exit fullscreen mode

44. What are React fragments?

React Fragments allow you to group multiple elements without adding an extra DOM node. It's useful when rendering adjacent elements.

Example:

<React.Fragment>
  <h1>Hello</h1><p>World</p>
</React.Fragment>
Enter fullscreen mode Exit fullscreen mode

45. What is React.memo?

React.memo is a higher-order component that prevents re-rendering of functional components if their props do not change. It's a performance optimization tool.

Example:

const MyComponent = React.memo(({ value }) => {
  return <div>{value}</div>;
});
Enter fullscreen mode Exit fullscreen mode

46. What is the purpose of refs in React?

Refs provide a way to access and manipulate DOM elements or React elements directly. They are typically used for:

  • Managing focus or text selection.
  • Triggering animations.
  • Accessing child component methods.

Example:

const inputRef = useRef(null);
<input ref={inputRef} />;
Enter fullscreen mode Exit fullscreen mode

47. What is the useRef hook, and how does it work?

useRef returns a mutable ref object whose .current property persists across re-renders. It's often used for accessing DOM elements or storing mutable values that don’t trigger re-renders.

Example:

const myRef = useRef(null);
useEffect(() => {
  myRef.current.focus();
}, []);
<input ref={myRef} />;
Enter fullscreen mode Exit fullscreen mode

48. How does useCallback work in React?

useCallback is a hook that memoizes a callback function, preventing it from being recreated on every render. It’s useful for optimizing performance, especially when passing functions as props to child components.

Example:

const handleClick = useCallback(() => {
  console.log("Clicked");
}, []);
Enter fullscreen mode Exit fullscreen mode

49. Explain the useEffect hook and its cleanup process.

useEffect allows you to perform side effects like fetching data or interacting with the DOM. The optional cleanup function is used to cancel effects like subscriptions or timers.

Example:

useEffect(() => {
  const timer = setTimeout(() => {
    console.log('Timer');
  }, 1000);

  return () => clearTimeout(timer); // Cleanup
}, []);
Enter fullscreen mode Exit fullscreen mode

50. What is the useReducer hook, and when would you use it?

useReducer is a hook for managing complex state logic. It’s a good alternative to useState when dealing with state transitions.

Example:

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

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    default:
      return state;
  }
}
Enter fullscreen mode Exit fullscreen mode

51. How do you optimize performance in React?

Common performance optimizations include:

  • Using React.memo to prevent unnecessary re-renders.
  • Using useCallback and useMemo to memoize functions and values.
  • Code splitting using React.lazy and Suspense.
  • Implementing pagination and lazy loading for large datasets.

52. What is code splitting in React?

Code splitting allows you to split your app into smaller bundles that can be loaded on-demand. React supports this using dynamic imports (import()) and React.lazy.


53. What is hydration in React?

Hydration refers to React taking over a server-rendered HTML structure and adding interactivity to it. It's a process where React attaches event listeners and state to pre-rendered static content on the client-side.


54. How does server-side rendering (SSR) work in React?

SSR is the process of rendering React components on the server into HTML and sending it to the browser. The browser then takes over with React’s hydration process, allowing the app to behave like a single-page application.


55. What is the difference between client-side rendering (CSR) and server-side rendering (SSR)?

  • CSR: The app is rendered entirely on the client side. The initial load is slower because all the JavaScript needs to be fetched and executed before rendering.
  • SSR: The app is rendered on the server and sent as HTML to the client, providing a faster initial load. After that, React takes over with client-side interactivity.

56. What is Static Site Generation (SSG) in React?

SSG pre-renders pages at build time rather than on each request (as in SSR). This approach improves performance by serving static HTML files, which are faster to load.


57. What are React portals, and how are they useful?

React Portals allow you to render children into a DOM node that exists outside the DOM hierarchy of the parent component. They’re useful for rendering elements like modals or tooltips outside the main application node.

Example:

ReactDOM.createPortal(
  <Modal />,
  document.getElementById('modal-root')
);
Enter fullscreen mode Exit fullscreen mode

58. What is reconciliation in React?

Reconciliation is the process through which React updates the DOM. React uses the virtual DOM to compare the current tree with the previous tree (diffing) and only updates the parts that changed.


59. What is the role of keys in React lists?

Keys are unique identifiers for list items in React. They help React identify which items have changed, added, or removed, allowing React to perform optimal updates and avoid unnecessary re-renders.


60. What is suspense in React, and how does it work with lazy loading?

Suspense is a component that lets you display a fallback UI while waiting for asynchronous operations like lazy loading. It works in tandem with React.lazy to render a component only when the import is complete.

Example:

<Suspense fallback={<div>Loading...</div>}>
  <LazyComponent />
</Suspense>
Enter fullscreen mode Exit fullscreen mode

61. What is Next.js, and how does it work with React?

Next.js is a React framework that enables server-side rendering, static site generation, and hybrid apps. It simplifies tasks like routing, API handling, and builds optimized React applications with built-in SSR and SSG.


62. What is Gatsby.js, and how does it work with React?

Gatsby.js is a React-based static site generator that creates fast and SEO-friendly static websites. It prefetches data, uses GraphQL to manage data, and optimizes for performance with features like image optimization and caching.

Top comments (0)