React Interview Questions

1. What is React and what are its key features?

The React library allows developers to build user interfaces (UIs) using JavaScript. The platform was developed by Facebook and is widely used to create dynamic and interactive web applications. In React, the user interface is divided into reusable components, which can then be combined to form complex user interfaces.

The following are some key features of React:

  • Virtual DOM
  • Component-based architecture
  • JSX
  • Unidirectional data flow
  • Virtual DOM diffing
  • React Hooks
  • Rich ecosystem and community support
  • 2. Differences between Functional Components and Class Components in React ?

    FeatureFunctional ComponentsClass Components
    SyntaxJavaScript functionsES6 classes extending React.Component
    State and LifecycleUse hooks like useState and useEffectAccess to lifecycle methods
    Code ComplexitySimple and lightweightMore verbose syntax
    PerformanceGenerally more performantSlightly less performant
    React HooksCan directly use hooksHooks cannot be used directly
    CompatibilityDesigned with newer features in mindLegacy, fully supported

    3. What is JSX in React? How does it differ from HTML ?

    JSX (JavaScript XML) extends the JavaScript language syntax used in React. You can write HTML-like code directly within your JavaScript code.

    import React from 'react';
    
    const App = () => {
      const name = 'John Doe';
      const age = 25;
    
      return (
        <div>
          <h1>Welcome to My React App</h1>
          <p>Name: {name}</p>
          <p>Age: {age}</p>
        </div>
      );
    };
    
    export default App; 
    Learn More

    4. Explain the concept of virtual DOM (Document Object Model ) in React and how it improves performance ?

    A virtual DOM is a lightweight copy of React's real DOM. It abstracts the HTML structure of a web page from the real DOM.

    There are several benefits to using this approach:

  • Efficient Updates
  • Faster Rendering
  • Batched Updates
  • Cross-Platform Support
  • 5. How does React handle state management ?

    React handles state management by allowing components to have their own state, representing their own data. The state can be initialized with hooks such as useState or by extending the React.Component class. In React, when the state of a component or child changes, the user interface is efficiently updated using the virtual DOM and diffing algorithm. Updates can be made by using functions like setState or the return setter function from useState. In more complex scenarios, React offers tools such as Context API, Redux, or MobX for managing and sharing state across components and the entire application.

    6. What is the significance of keys in React lists ?

    Whenever you render lists of elements dynamically in React, it's important to assign a unique "key" prop to each item. React uses the key prop to determine which items have changed, been added, or removed.

    The significance of keys in React lists

  • Efficient Reconciliation
  • When updating lists, React uses keys to perform efficient reconciliation. As a list is rerendered, React compares the new list with the previous one. As a result, it can make precise updates in the DOM without re-rendering the entire page, identifying the items that have been added, removed, or re-ordered using the keys.

  • Enhancing Performance
  • React's rendering and update processes are optimized by providing keys. This prevents unnecessary re-rendering of unchanged items, thus improving performance and smoothing out the user experience.

  • Stable Component Identity
  • Keys help React maintain component state correctly by providing a stable identity for each item. When reordering or modifying a list without keys, you run the risk of unintended side effects, such as incorrect state updates or losing component focus.

    //Example 
    function ListComponent() {
      const items = [
        { id: 1, name: "Item 1" },
        { id: 2, name: "Item 2" },
        { id: 3, name: "Item 3" },
      ];
    
      return (
        <ul>
          {items.map((item) => (
            <li key={item.id}>{item.name}</li>
          ))}
        </ul>
      );
    } 

    7. Explain the React component lifecycle methods.

    Mounting Phase

  • constructor()
  • static getDerivedStateFromProps()
  • render()
  • componentDidMount()
  • Updating Phase

  • static getDerivedStateFromProps()
  • shouldComponentUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()
  • Unmounting Phase

  • componentWillUnmount()
  • 8. What are controlled components in React ?

    A controlled component in React controls elements, such as input fields, select dropdowns, or text areas, based on its state. Value changes are handled by updating the component's state, which is used as the single source of truth.

    import React, { useState } from 'react';
    
    function ControlledComponentExample() {
      const [inputValue, setInputValue] = useState('');
    
      const handleInputChange = (event) => {
        setInputValue(event.target.value);
      };
    
      return (
        <div>
          <input
            type="text"
            value={inputValue}
            onChange={handleInputChange}
          />
          <p>Input value: {inputValue}</p>
        </div>
      );
    }
    
    export default ControlledComponentExample;  

    8. How does React Router work and what are its advantages ?

    The React Router library allows you to handle navigation and routing within your React applications. According to the current URL, it provides a declarative way of defining routes and rendering different components.

    //Switch and Route
    function App() {
      return (
        <Router>
          <Switch>
            <Route exact path="/" component={Home} />
            <Route path="/about" component={About} />
            <Route path="/contact" component={Contact} />
            <Route component={NotFound} />
          </Switch>
        </Router>
      );
    }
    
    
    //Navigation Link
    import { Link } from 'react-router-dom';
    
    function Navigation() {
      return (
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
            <li>
              <Link to="/contact">Contact</Link>
            </li>
          </ul>
        </nav>
      );
    }  

    9. What is the purpose of the setState() method in React ?

    A components setState() method updates its state and triggers a re-rendering of itself, as well as its child components. Using this method, you can ensure that your UI reflects your app's current state and manage dynamic data efficiently.

    this.setState((prevState) => ({ count: prevState.count + 1 }));

    10. How to pass data from a child component back to its parent component ?

    Callback Functions:Parent components can define callback functions and pass them as props to the child components. Using this callback function, the child component can send data to its parent.

    Context API: The Context API enables you to share context between parents and children. The parent component can listen to changes to the context and update the context as needed.

    State Management Libraries: Redux or MobX state management libraries can be used if your application involves complex state management.