Top 50+ React Interview Questions (2024)

Nishil Patel

Nishil Patel

Jun 28, 2024

15 min read

Share

Top 50+ React Interview Questions (2024)

This article covers the top 50+ React interview questions, from beginner to advanced levels. Check out the most asked questions, for you to ace your React interviews.

Table of Contents

1.

Introduction

2.

Beginner Level Questions

3.

Intermediate Level Questions

4.

Advanced Level Questions

5.

FAQs

Introduction

React’s popularity is off the charts! It's no surprise that React skills are highly sought after. A Statista report puts React on the second rank (as of 2023) in the list of most used frameworks by developers, globally, with a market share of a whopping 40.58 %. The demand for React developers is steady and it’s not gonna halt, at least for a good number of years.

This article covers the top 50+ React interview questions you’ll most likely come across while appearing for your interviews. It covers everything, from basic to advanced level questions, for you to absolutely blaze through your interview sessions.  

Beginner Level Questions

1 - What is React?

React is an open-source JS library used for building user interfaces. It’s based on using reusable components to create front-facing UIs. This approach of using components helps break down complex UI elements into small reusable functions. They act as small building blocks and are very similar to using Lego bricks to create very complex UIs that are easy to scale and maintain. React is also used to develop mobile apps using React Native.

2 - What are the top features of React?

React offers many features that make it a powerful tool to build all kinds of websites and apps.

Here are some noteworthy features of React:

  • Components — React apps are built using modular and reusable components. These are nothing but small functions. These functions encapsulate the UI functions and something called the state. They work on the principle of separation of concerns, making code much more organized and maintainable.
  • JSX — JSX stands for JavaScript Syntax Extension. It allows you to include HTML right inside your code and is very similar to adding HTML-like code using JS functions. This makes it much easier to write UI elements code in the form of JS reusable components.
  • Virtual DOM — a virtual DOM is an in-memory representation of the real DOM. React creates the exact blueprint of the real DOM and manipulates it only when necessary. This allows React to run efficient UI re-renders with updated content.
  • Unidirectional data flow — the data in React apps flows from the parents to the child components. This drip of one-way or unidirectional data (stored as a state) flow occurs through props (properties). This flow only occurs from a higher to a lower state, making the data flow unidirectional, hence the name. This makes your application’s state easier to manage.
  • Declarative — React uses a declarative approach, which means you describe what your UI should look like for a given state. Instead of writing code to manipulate the DOM directly (imperative), you tell React the desired outcome, and React handles the "how" of making those changes.

3 - What is a “state” in React?

state helps manage data across a React app. It's the space where the fetched data—typically from an API—lives or gets stored. This data is then communicated to the UI elements as per the internal code logic.

Here are some features of the React state:

  • Holds data specific to that component that can change over time.
  • Mutable and can be updated with code logic.
  • Triggers a component re-render whenever it changes.
  • Used for data that reflects the component's internal state or user interaction.
  • Functional components can manage state using React Hooks (since React 16.8).

4 - What are “props” in React?

props are short forms for properties. It’s a naming convention generally used by React developers to denote properties. Just like the state, props are also a fundamental concept in React. Here’s what React props typically mean and are used for:

  • Way to pass data down from parent components to child components.
  • Read-only within the lower level (or the receiving) child component.
  • Unlike states, props are immutable and cannot be modified by the child component.
  • Used for configuring a component or providing external data.
  • Can be used with both functional and class-based components.

Here’s the basic syntax for using props in React:

import React from 'react';

function UserCard(props) {
  return (
    <>
      <h1>{props.name}</h1>
      <p>{props.email}</p>
    </>
  );
}

export default UserCard;

5 - What are SPAs?

SPA stands for Single-Page Application. They are web apps that load a single HTML page in the browser and dynamically update the content as the user interacts with it. Unlike traditional web apps that reload the entire page for each navigation, SPAs use JS functions to fetch data from the respective server with API calls or using the app state. This data updates the DOM without full page reloads, making the app extremely fast and snappy to use.

Also Read: Top 20 Chrome Extensions for Web Developers

6 - How does React’s definition fit with SPAs?

React is built on the principle of re-usability. It provides building blocks and flexibility to create dynamic and interactive UI elements. These perfectly fit the core aspects of a Single-Page Application. Here’s how:

  • React's component-based structure and focus on UI updates make it perfect for creating interactive elements of a SPA.
  • The virtual DOM ensures efficient updates to the real DOM, improving the performance of the SPAs.
  • Popular libraries like React Router are specially developed to handle routing and navigation within a React SPA, making it easy to create latency-free apps with crisp navigation and blazing load speeds.

7 - What are React Hooks?

React hooks are pre-defined functions that allow you to manipulate React state and other features directly from functional components. They were first introduced in React 16.8. The prior versions used class components for state management and lifecycle methods. Hooks are very popular due to their easy-to-use syntax with less boilerplate code.

Capture Front-end Issues with Console Logs

8 - What are some features of React Hooks?

Here are some important features of React Hooks:

  • React Hooks like useState allows you to manage state within functional components.
  • Hooks promote code reusability.
  • Enables you to create custom hooks to create reusable functions to include custom logic for state manipulation.
  • Using hooks with functional components makes react code much more readable and easier to handle compared to class components with complex state management syntax and logic.

Here’s an example of the modifying state using the useState React Hook:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  const handleClick = () => setCount(count + 1);
  return (
    <>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Increase</button>
    </>
  );
}
export default Counter;

9 - Explain the concept of virtual DOM in React.

The Document Object Model (DOM) is a tree structure that represents a web page's content. It allows browsers to render and manipulate the page. While DOM manipulation offers interactivity, it can be slow, especially for frequent updates or complex UIs.

React's virtual DOM acts as an in-memory representation of the real DOM. It's like a lightweight copy built entirely with JS objects. This virtual DOM mirrors the real DOM's structure but is much faster to modify.

Here's how it benefits React:

  • Efficient updates —  when your React component's state changes, React updates the virtual DOM first. Then, it calculates the minimal differences between the old and new virtual DOM.
  • Faster Performance — instead of directly updating the real DOM, React applies only the necessary changes, significantly improving performance.

10 - What are "keys" in React?

Keys in React are special string identifiers (attributes). They are assigned to elements within the lists of items being rendered and serve as a unique identifier for each item in the list. This helps React optimize UI updates and re-rendering. React uses these unique keys to figure out what elements to manipulate, leaving the other elements untouched.

Facing React Errors? Report Them, Super-fast

11 - Why are "keys" important?

Here are some reasons that make "keys" extremely important:

  • Keys help in optimizing updates using virtual DOM. This significantly improves app performance. When the data in your list changes (items added, removed, or reordered), React uses keys to determine which specific items need to be updated, added, or removed in the DOM. This avoids unnecessary re-renders of the entire list.
  • They provide a stable identity for components within the list. This is particularly important when using components to represent list items. This ensures that React associates the correct component with the suitable data item throughout its lifecycle.

12 - What are events in React?

Events in React represent user interactions with the UI components. These can be clicks, form submissions, key presses, or any action that triggers a response in the app. React uses a declarative approach to handle events to easily manage interactivity.

13 - How do you handle React events?

There are two important ways to handle events in React:

Using event handlers:

  • They are functions that define what happens when a specific event occurs.
  • Typically attached to JSX elements using camelCase event names (e.g., onClick for clicks).
  • When the event occurs, the event handler function is executed, and you can write logic to update the component's state or perform custom actions.

Synthetic events:

  • Synthetic events are cross-browser-compatible abstractions.
  • They are used in place of native browser events to run custom logic.
  • They ensure consistent behavior across different browsers.
  • With synthetic events, the event handler function receives an event object as an argument, with details about the event like the type of event and any additional data.

Here’s an example that shows how to handle button clicks in React using the onClick event handler:

import React, { useState } from 'react';

function ButtonClick() {
  const [msg, setMsg] = useState("");

  const handleClick = () => {
    setMsg("Button Clicked!");
  };

  return (
    <div>
      <button onClick={handleClick}>Click Here!</button>
      <p>{msg}</p>
    </div>
  );
}

export default ButtonClick;

14 - How do you fetch data in React apps?

Here are some ways to fetch data in React apps:

  • Fetch API — It's a built-in browser API to manage HTTP requests and a native way to get server data. With the fetch() function, you can send requests to servers and also retrieve data. React functional components typically use the useEffect() hook to manage the data fetching process and update the component state with the fetched data.
  • Third-party libraries — Libraries like Axios and SWR are popular choices for data fetching in React apps. They often use a promise-based approach and offer features like automatic JSON parsing, interceptors for error handling, cancellation support, and caching capabilities (like SWR). These libraries can simplify the process and reduce boilerplate code compared to the Fetch API.
  • React Query — React Query is another popular library for data fetching in React. It’s great for managing, fetching, caching, and refetching data. It also simplifies the process and reduces a ton of boilerplate code.
  • Custom Hooks — You can create custom hooks to include data-fetching logic in React apps. Additionally, you can use the Fetch API or third-party libraries like Axios within your custom hooks. This helps create reusable components with specialized use cases and gives you more control over the data-fetching process. Custom hooks are reusable functions that allow you to share state and logic between components.

Also Read: How does the Nullish Coalescing Operator(??) works in JS?

15 - How do you add comments in React code?

There are two ways to add comments code in React. However, it can vary depending on whether you're working with regular JS or JSX. Here’s how it works:

#1 - Add Comment JS code within React — use the standard JS comment syntax for both single-line and multi-line comments.

Here’s how:

  • Single-line comment
// This is a single-line comment
  • Multi-line comment:
/* This is a multi-line comment
that can span across multiple lines */

#2 - Add Comments in JSX code — since JSX gets converted to JS before running, you can't use the standard JS comments directly.

Here’s the syntax:

{
  /* This is a comment within JSX */
}

Here's a quick overview of the above:

  • Use // to comment within your JS code.
  • Use /* */ to provide longer text descriptions or temporarily disable JS code.
  • Use {/* */} to comment within JSX.

Present-day text editors (like VS Code) auto-insert the correct comment syntax when you use keyboard shortcuts to comment (when properly configured to handle React code).

16 - What are fragments in React and how are they written?

Fragments help group multiple JSX elements together without adding an extra DOM node. This is useful when you need to return multiple elements from a component but don't want unnecessary HTML elements like <div>.

Here's how to write React fragments:

#1 - Fragment component — React provides a built-in Fragment component that you can import. If you want to skip the import, you can also directly use React.Fragment instead.

Here’s an example with the import statement:

import React, { Fragment } from "react";

function MyComponent() {
  return (
    <Fragment>
      <h1>Welcome</h1>
      <p>This is my component!</p>
    </Fragment>
  );
}

#2 - Use the short-hand syntax (<> ... </>) — you can also write fragments using the short-hand syntax.

Here’s how:

import React from "react";

function MyComponent() {
  return (
    <>
      <h1>Welcome</h1>
      <p>This is my component.</p>
    </>
  );
}

17 - What are inline styles in React? Explain with an example.

Inline styles in React are a way to apply CSS styles directly to an element within the JSX code. It’s not a preferred way to write CSS for larger apps and is typically used in demos or small-scale styling.

Here’s the syntax:

import React from "react";

function MyComponent() {
  const myStyle = {
    color: "blue",
    fontWeight: "bold",
    fontSize: "1.2rem",
  };

  return <h2 style={myStyle}>Hello World!</h2>;
}

18 - How do you use the map() method in React?

The JS map() method is typically used in React apps to transform array data into JSX elements. React then renders it on the UI.

Here’s an example:

import React from 'react';

const MyComponent = ({ data }) => {
  return (
    <ul>
      {data.map((item, index) => (
        <li key={index}>{item}</li>
      ))}
    </ul>
  );
};

export default MyComponent;

Here’s a breakdown of the code:

  • MyComponent takes an array named data (as a prop).
  • The return statement contains an unordered list (ul).
  • map() method iterates over the data array.
  • The callback function takes each item and its index as args.
  • The li element for each item has index values as unique keys.

Next, MyComponent is rendered within the App component.

Here’s how:

import MyComponent from "./MyComponent";
const items = ["Item 1", "Item 2", "Item 3"];
function App() {
  return (
    <>
      <MyComponent data={items} />
    </>
  );
}

Here’s a breakdown of the above code:

  • MyComponent gets imported for reuse.
  • The “items” have some sample data.
  • The App function renders the MyComponent, passing the items array as the data prop.

Intermediate Level Questions

19 - How do you manage complex states in React apps?

Managing complex states in React can be tricky owing to its capabilities to help build super complex apps. Here are some ways to champion complex state handling in React:

Using React Hooks:

  • Use useState() and useReducer() Hooks to manage component-level state.
  • useState works great for simple state values, while useReducer helps manage complex state objects with predictable updates.
  • Suited for smaller apps or components with isolated states.

Lifting State:

  • Sharing state is another way to manage complexity.
  • You can "lift" the state up to the closest common parent component that needs it.
  • Helps avoid prop drilling (passing props through many levels) and keeps state management centralized.

Context API:

  • Using the built-in Context API is a popular way to avoid prop drilling while managing complex states.
  • It's useful for sharing global state or state needed by deeply nested components.
  • Good for simpler state-sharing scenarios.

State Management Libraries:

  • Dedicated libraries are typically used for complex state management scenarios.
  • Popular options include React-Redux, Redux Toolkit, MobX, and Zustand.
  • These libraries provide centralized stores, actions for state updates, and mechanisms for managing side effects.

20 - What is prop drilling?

Prop drilling refers to the process of passing data down through multiple nested components in your app's hierarchy.

Typically, it’s used to pass data from a parent component to its child components, and then potentially down to even deeper child components. This nested data passing goes on multiple levels until it reaches the component that actually needs the data. Passing data a few levels deep is considered okay, but after that, it’s not recommended.

21 - Why should you avoid prop drilling?

Here are some top reasons to avoid prop drilling:

  • Increased code complexity — as the component hierarchy grows deeper, prop drilling can lead to complex code and becomes a pain to handle.
  • Debugging becomes difficult — if there are issues with the data being passed, debugging becomes a challenge. Tracing an error several levels deep can be really annoying.
  • Affects code scalability — passing information in such a complex way can hinder the app’s scalability. It makes code very difficult to understand, read, and maintain.
  • Tight coupling of components — prop drilling also sacrifices flexibility and ease of use for which React is loved for. Tightly coupled components rely on props being passed down correctly. Even the smallest bug in one component can have unintended changes in another.

22 - What are the ways to avoid prop drilling?

Here are some ways to avoid prop drilling in React apps:

  • Context API: Using the built-in Context API provides workflows to share data across components without explicitly passing props down every level.
  • State management libraries: Libraries like React-Redux and Redux Toolkit offer a centralized store for the app state, making data accessible from any component.

Capture React Issues with DevTool Logs

23 - What are Higher Order Components (HOCs)?

HOCs are a pattern for reusing component logic. They are functions that take a component and return a new component with enhanced functionality. It’s like gearing up the components with superpowers. Typically used for custom use cases or in specialized scenarios, HOCs are useful for code sharing and writing custom code for things like authentication or data fetching in multiple modules.

24 - What’s the difference between class-based and functional components?

Here are some key differences between class-based and functional React components:

Class-based components:

  • They are written using JS ES6 classes, extending the React.Component class.
  • With class-based components, this.setState() is used to manage the internal state.
  • They offer lifecycle methods like componentDidMount for actions at specific executing points in a component's lifecycle (mounting, updating, unmounting).
  • More complex to write due to class syntax and lifecycle methods.

Functional components:

  • Written with JS functions that accept props as arguments and return JSX (describing the UI).
  • Traditionally stateless, can manage state easily using useState Hook.
  • No built-in lifecycle methods, but Hooks like useEffect can handle similar functionalities.
  • Simple and easy to understand compared to class components.

25 - Explain the useState Hook with a short example.

The useState Hook lets you manage state in React functional components. You can declare state variables and a fitting function to update them directly within that component.

Here's an example:

import React, { useState } from 'react';

function Counter() {
  // Declare state variable 'count' with initial value 0
  const [count, setCount] = useState(0);
  // Function to increase count
  const handleClick = () => {
    setCount(count + 1);
  };

  return (
    <>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Increase</button>
    </>
  );
}

export default Counter;

26 - What is the useEffect Hook and when is it typically used?

The useEffect React Hook helps manage side effects in functional components. Unlike useState which manages internal state updates, useEffect lets you run actions outside the component's render cycle (side effects), such as:

  • Fetching data from external APIs
  • Setting up subscriptions
  • Manually manipulating the DOM (use with caution)
  • Running timers

Here’s when useEffect is typically used:

  • With operations that interact with external resources or modify the DOM directly.
  • For logic that needs to run after the component renders (e.g., async data fetching).
  • To set up cleanup functions (to prevent memory leaks).

27 - What are arrow functions and why are they preferred in React apps?

Arrow functions were released in the JS ES6 language update and provide a concise syntax for writing JS functions. They are super useful for places where a function is defined only once or within a compact expression. It makes them a go-to option for writing React code.

Here’s how an arrow function in React typically looks like:

import React from "react";

const MyComponent = () => (
  <>
    <h1>Hello World!</h1>
  </>
);

28 - How are arrow functions typically used in React?

Here are some ways in which arrow functions are typically used:

#1 - With functional components — arrow functions provide a clean way to write React functional components. Here’s how:

const MyFunc = () => (
  <>
    <h1>My Test Component!</h1>
  </>
);

#2 - For event handlers — JSX lets you directly define event handlers using arrow functions. Here’s how:

<button onClick={() => console.log("Button clicked!")}>Click Me</button>;

#3 - For callback functions — when passing functions as props or within other functions, with arrow functions, you can concisely write the callback logic. Here’s how:

const handleClick = (message) => alert(message);
<MyComponent onClick={() => handleClick("Button pressed!")} />;

29 - What is CORS? Explain with a short example.

CORS stands for Cross-Origin Resource Sharing. It's a default security mechanism built into web browsers. It restricts how a web page from one domain can access resources from a different domain.

For instance, let’s say a web page on xyz.com wants to load data from an API from a different domain (example: abc.com/api/v1) than what it's configured for. Normally, browsers won’t allow this due to a protocol called the Same-Origin Policy. This protocol restricts web pages from making requests to resources on different domains than the one that served the page.

CORS provides a way for the server to tell the browser on xyz.com that it's okay and safe to access the data from abc.com/api/v1.

30 - How is CORS typically used in React app development?

React apps, like many other web apps, typically fetch data from external APIs to populate content or provide functionalities.

For example, consider a React app's frontend client running on http://localhost:3000 that needs data from an API server on http://localhost:5000.

Here, the client and server reside on different origins (due to different ports), and CORS comes into play. Without CORS enabled on the API server, the browser blocks the React app's requests, preventing data fetching.

As a development workaround (not recommended for production due to security implications), you can set up a proxy server that forwards requests from the React app to the API server. The proxy can be helpful in development by simplifying CORS configuration, as the actual CORS configuration needs to be done on the API server itself.

31 - What are the different methods to style React components?

Here are some popular ways to style React components:

  • Inline Styles — styles are added directly to JSX elements using the style attribute. This keeps things self-contained but can make code cluttered. It’s not recommended for production apps.
  • External Stylesheets — separate CSS files are used to define styles. This promotes separation of concerns but requires managing multiple files.
  • CSS-in-JS Libraries — libraries like styled-components let you write styles in JS using template literals. It's a very popular and scalable way of styling in React.
  • CSS Modules — styles are scoped to the component using a unique class name generation process. This prevents style conflicts but requires additional configuration.
  • Utility-First Frameworks (e.g., Tailwind CSS) — with these, pre-built CSS classes for common styles are used. This offers rapid development but can lead to less maintainable styles. They are just as popular as using styled-components and generally loved by developers.

Advanced Level Questions

32 - What are the lifecycle methods in React? Explain each one in brief.

React lifecycle methods consist of different phases where specific methods are called. You can control the component's behavior at various stages with these methods. Here's more on each:

Mounting Phase

  • constructor(props) — initializes the component's state using this.state = {...}.
  • render() — generates the virtual DOM representation based on the current props and state.
  • componentDidMount() — invoked immediately after the component is inserted into the DOM.

Updating Phase

  • shouldComponentUpdate(nextProps, nextState) — allows optimization by returning false if the component shouldn't re-render based on upcoming props and state changes.
  • getDerivedStateFromProps(nextProps, prevState) — a static method that updates the state based on changes in props.
  • componentDidUpdate(prevProps, prevState) — called after the component has been updated, and the DOM reflects the changes.

Unmounting Phase

  • componentWillUnmount() — invoked just before a component is removed from the DOM.

33 - What is conditional rendering?

It’s a technique that lets you control what content gets displayed on the screen based on some conditions. This helps create dynamic UIs that adapt to changes in data or due to user interactions.

34 - How can conditional rendering be achieved in React?

Here are the top ways to achieve conditional rendering in React:

  • If-else statements — you can use the good ol’ if and else statements to write the logic for what to render based on some conditions.
  • Ternary operators — they provide a shorthand JS syntax to write conditional statements within JSX. They are incredibly useful for writing concise conditional code in various scenarios.
  • Logical AND operator (&&) — they are written with an even shorter syntax for conditional rendering. If the expression before the && operator evaluates to true, the JSX after it is rendered. Otherwise, nothing is rendered.

35 - What are ternary operators? How are they used in React apps?

Ternary operators are a JS shortcut syntax for writing conditional statements. They are typically used in React code to write conditional rendering logic.

Here’s how it’s written in a React component:

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  return <>{isLoggedIn ? "Welcome back!" : "Please sign up."}</>;
}

Here’s what the code does:

isLoggedIn is a prop passed to the Greeting component.

The ternary operator checks if isLoggedIn is true.

  • If true, it renders "Welcome back!".
  • If false, it renders "Please sign up.".

36 - Can you use hooks in conditional statements in React components?

No, you cannot directly use hooks inside conditional statements in React components. Here's why it's not recommended:

  • Order of execution — React relies on the order in which hooks are called to maintain state consistency across renders. If a hook is conditionally invoked (e.g., inside an if statement), it might not always execute during every render. This can disrupt the expected order of hooks and cause unexpected behavior or bugs.
  • Stale state — Hooks like useState manages component state. If you skip a hook call based on a condition, it can lead to stale state. For example, if you conditionally call useState inside an if block, the state won’t update as expected.

37 - What are forms in React?

React form lets you collect user input and handle form submissions. It works the same as other web app forms. React uses a different syntax for it. You can write one by combining HTML and JSX.

It includes:

  • HTML elements — they help build the skeleton of a form. A typical React form contains HTML form elements like <input>, <textarea>, <select>, and <button>. These define the input type for users to provide (text, password, selection, etc.).
  • Controlled components — React forms are often written using controlled components. Here, the form data is managed by the component's state, and any changes in the form field values are reflected in the state.
  • State management the useState hook is primarily used in React forms. It manages the state of the form fields. The state holds the current values entered by the user in each field.
  • Event handlers — event handlers are attached to form elements like <input>. When you interact with the form (for example, typing in an input field), the corresponding event handler gets triggered. These functions then update the component's state with the new values.
  • Form submission — when you submit the form ( by clicking a submit button), a form submission event gets triggered. You can handle this event using an event handler and perform actions like sending the form data to the connected server or performing validation checks.

38 - Give a short example of a React form.

Here’s an example code for a simple React form:

import React, { useState } from "react";

function SimpleForm() {
  const [message, setMessage] = useState("");
  const handleChange = (event) => {
    setMessage(event.target.value);
  };

  return (
    <form onSubmit={(e) => e.preventDefault()}>
      {/* To prevent default form submission */}
      <label>
        Message:
        <input
          type="text"
          name="message"
          value={message}
          onChange={handleChange}
        />
      </label>
      <br />
      <button type="submit">Submit</button>
    </form>
  );
}

Here’s a breakdown of the code:

  • The SimpleForm component manages a single state variable message using useState.
  • The handleChange function updates the message state whenever you type in the input field.
  • The form JSX includes a single input field for a message and a submit button.
  • The onSubmit event handler prevents the default form submission behavior (refresh) but can be replaced with your desired action (for example, logging the message).

39 - What are controlled and uncontrolled components?

Controlled and uncontrolled components are two key approaches to building React forms.

Controlled components keep form data within the component's state. It gives you more control and makes validation easier. Whenever you type or interact with the form, the component updates its state and triggers a re-render to reflect the changes. This controlled approach requires more code for state management but offers better predictability.

Uncontrolled components, on the other hand, store data directly within the DOM elements. You can access and update this data using refs (a way to directly access DOM or React elements created within your components) in your React code. While simpler for basic forms, uncontrolled components make validation trickier as it can only happen after form submission. They also can be less predictable due to the data living outside the component's state.

40 - What is a React Router?

React Router is a popular library to manage navigation in React apps. It enables you to create SPAs where users can navigate between different views or components without entire page reloads.

Here's what you can do with React Router:

  • Define app routes — you can define different routes (URL paths) that map to specific components.
  • Render components — based on the current URL, it lets you render the corresponding component that handles that particular view.
  • Manage URLs — you can keep the URL in the browser address bar in sync with the currently displayed component.
  • Handle navigation — it provides components like Link for declarative navigation within your app. It allows you to click on links and smoothly transition between views.

41 - What is Memoization?

Memoization is an optimization technique that helps improve your React app performance. It prevents unnecessary re-renders of components by caching the results of expensive computations or function calls based on their inputs.

42- What are performance Hooks?

Performance Hooks help optimize your app’s performance with memoization at its core. These Hooks don't directly change how the UI looks or behaves but rather optimize how React renders and updates the components. There are two of them:

  • useMemo — it lets you memoize the results of expensive calculations or derived data within your component. With useMemo, if the args haven't changed since the last render, the cached result is used instead of recalculating it. It’s especially beneficial for memoizing heavy computation results.
  • useCallback — this hook helps memoize callback functions used within your component. Similar to useMemo, it caches the function itself based on its input. If the input is unchanged, React ensures the same function reference is returned. This prevents unnecessary re-creation of the function on every render. This is particularly useful for callback functions passed as props to child components or when used with event listeners.

43- What leads to memory leaks in React apps that use functional components?

Functional components aren't inherently prone to memory leaks, but how you use certain features within them can lead to issues. Some common causes include:

  • Uncleaned event listeners on DOM elements.
  • Uncleared functions in useEffect functions.
  • Unhandled subscriptions, network requests, timers, and async tasks.
  • Large and unmanaged states.
  • Improper closures.
  • Unnecessary circular references.

44 - How do you prevent memory leaks?

Here are some ways to prevent memory leaks in React apps:

  • Use clean-up functions with useEffect — when adding event listeners to DOM elements within your component, use the useEffect Hook with a cleanup function. The cleanup function removes the event listener when the component unmounts, preventing memory leaks.
  • Remove unnecessary functions — similar to event listeners, if your component uses functions that aren’t required anymore, (for example, timers, async tasks, network requests, subscriptions), again, clear them up with the cleanup functions (typically in useEffect Hook). This ensures the component doesn't hold onto unnecessary references or functions after it unmounts.
  • Manage state updates — avoid storing excess data in the component state, especially when it's not actively used. Large amounts of unused data in state can contribute to memory leaks.
  • Use performance Hooks —  utilize the useMemo Hook to memoize components. It prevents unnecessary re-renders and helps ease up on memory leaks. Similarly, utilize the useCallback to memoize callback functions. They help keep away from creating new references on every render.

46 - What are “Refs” in React?

Refs (short for references) allow you to directly access DOM elements or React components created within your component. They provide a way to interact with elements outside of the usual React data flow (where props are used between parent and child components for communication).

47 - When are “Refs” generally used?

It’s not recommended to use Refs too often. It’s because it defeats the purpose of re-usability and affects app performance to some extent. However, here are some scenarios where refs can come in handy:

  • Focusing elements — can be used to programmatically focus form or other interactive elements.
  • Manipulating the DOM manually — can be used for directly manipulating the DOM in specific scenarios (not recommended in favor of using React's state management for UI updates).
  • Integrating with third-party libraries some external libraries may require direct DOM access, and refs can be used to facilitate this integration.

48 - What is React Suspense?

React Suspense allows components to pause rendering and display a fallback UI. It happens while waiting for async operations to finish. These operations typically involve fetching data from an API or loading other components dynamically.

Here’s how it works:

  • Waiting for async operations — a component can wrap its content with the <Suspense> component. This tells React to pause rendering of that content until a specific condition is met.
  • Fallback UI — inside the <Suspense> component, you can provide a fallback UI (like a loading spinner or placeholder content) that will be displayed while the async operation is still in progress.
  • Resuming Render — once the async operation finishes (for example, data is fetched), React resumes rendering the content within the <Suspense> component. The fallback UI then hides.

Read More: React Suspense: Work Better with Async Data

49 - What is Redux?

Redux is a popular open-source JS library for managing app state. It's particularly well-suited for complex React apps but can be used with other frameworks like Angular and Vue.

50 - What are the benefits of using Redux?

Here are some key benefits of using Redux:

  • Centralized state — provides a single source of truth for your app’s state. It makes it easier to understand, maintain, and debug.
  • Predictable state updates — enforces unidirectional data flow through reducers, which are pure functions. This ensures predictable state updates and provides a clear view and route of how the state changes.
  • Helps in testing better — with a centralized state and pure reducers, testing Redux apps becomes more straightforward. You can easily isolate components and predict their behavior based on state changes.
  • Easy to debug — Redux DevTools lets you inspect past states and actions. It's very helpful for identifying the root cause of issues.
  • Very scalable — for complex apps with many components and interactions, Redux can help manage state effectively and avoid prop drilling.

51 - What are the core components of Redux?

Redux has three core components that manage app state:

  • Actions — plain JS objects describing what action just took place in the app (for example, adding an item to a shopping cart list).
  • Reducer — a pure function that takes the current state and an action, returning the new state based on the action type (for example, reducer that adds a cart item to the state based on an action).
  • Store — a central object or data store that holds the entire app state. Also provides methods to get the state, dispatch (send signals for state changes) actions, and subscribe (components can listen for updates) to state changes.

52 - What is a pure component in React?

A pure component always renders the same output for the same props and state. This concept is borrowed from functional programming, where pure functions produce the same result for the same arguments.

53 - Compare smart components and dumb components in React.

FeatureSmart ComponentsDumb Components
PurposeManages data, logic, stateRenders UI based on props
DataFetches or holds app dataReceives data as props
LogicHandles complex business rulesNo internal logic
StateManages app stateNo internal state
ReusabilityLower (tied to app logic)Higher (reusable for UI)
ImplementationClass or functional with HooksTypically functional

54 - What is the Strict Mode in React?

Strict Mode is a development tool that helps you catch potential issues in your code early on. It doesn't directly change how your application works but rather enables extra checks and warnings during development.

Here are some noteworthy ways in which it helps write React apps:

  • Identifying deprecated APIs — highlights the usage of legacy or deprecated React APIs that might be removed in future versions.
  • Detecting double rendering issues — can help identify components that might be triggering extra re-renders due to issues like side effects or outdated state updates.
  • Stricter referencing — enforces stricter rules around how refs (references to DOM elements) are used, helping to prevent potential bugs related to ref management.

FAQs

SSR, or server-side rendering, is a technique that lets you generate the initial HTML of your app right from your server. This is great for SEO and initial load performance, as the browser gets a ready-made page instead of having to build it from scratch.

Written by

Nishil Patel | CEO & Founder

Follow

Nishil is a successful serial entrepreneur. He has more than a decade of experience in the software industry. He advocates for a culture of excellence in every software product.

Subscribe to our updates

Meet the Author: Nishil Patel, CEO, and Co-founder of BetterBugs. With a passion for innovation and a mission to improve software quality.

We never spam.

Nothing here!
Show us some love 💖. Try BetterBugs today if you haven’t already. A quick feedback and a rating on our Chrome web store page would be awesome!

Share your experience with the founderhere!

Don’t wait! Start reporting now.