Top 30 ReactJS Interview Questions and Answers

Learn and master ReactJS with Top 30 Interview Questions and Answers often asked in technical interviews.

1. What is React?

React is a JavaScript library for building user interfaces.

It allows developers to create reusable UI components and efficiently update the UI when the underlying data changes.

2. What is JSX?

JSX is a syntax extension for JavaScript that allows you to write HTML-like code in your JavaScript files.

It is used in React to define the structure and content of components.

// Example of JSX

const element = <h1>Hello, World!</h1>;

3. What is a React component?

A React component is a reusable building block for creating UI elements.

Components can be either class components or function components.

// Example of function Greeting

   function Greeting() {
     return <h1>Hello, World!</h1>;
   }

   // Example of a class component

   class Greeting extends React.Component {
     render() {
       return <h1>Hello, World!</h1>;
     }
   }

4. What is the difference between functional and class components?

Functional components are JavaScript functions that accept props as an argument and return JSX.

Class components are ES6 classes that extend the `React.Component` class and define a `render` method to return JSX.

Functional components are simpler and recommended for most use cases.

5. What are props in React?

Props (short for properties) are used to pass data from a parent component to a child component.

Props are read-only and should not be modified by the child component.

   function Greeting(props) {
       return <h1>Hello, {props.name}!</h1>;
   }

   // Usage: <Greeting name="John" />

6. What is state in React?

State is an internal data store of a component. It is used to manage component-specific data that can change over time.

State should be initialized in the constructor and updated using the `setState` method.

// Example of using state
class Counter extends React.Component {
     constructor(props) {
       super(props);
       this.state = { count: 0 };
     }
     increment() {
       this.setState({ count: this.state.count + 1 });
     }
     render() {
       return (
         <div>
           <p>Count: {this.state.count}</p>
           <button onClick={() => this.increment()}>Increment</button>
         </div>
       );
     }
   }

7. What is the difference between props and state?

Props are used to pass data from a parent component to a child component, while state is used to manage component-specific data that can change over time.

Props are read-only and passed down from the parent, while state is internal to the component and can be modified using `setState`.

8. What is the purpose of the `render` method in a React component?

The `render` method is a required method in a React component. It returns the JSX that defines the structure and content of the component.

The `render` method should be pure and not modify the component’s state or props.

9. What is the Virtual DOM in React?

The Virtual DOM is a lightweight representation of the actual DOM. React uses the Virtual DOM to perform efficient updates by comparing the previous and current states of the Virtual DOM and applying the minimal necessary changes to the actual DOM.

10. What is the reconciliation process in React?

See also  Top 50 DMBS Interview Questions Answers

Reconciliation is the process of updating the actual DOM to match the desired state defined by the Virtual DOM.

React’s reconciliation algorithm efficiently determines the changes that need to be made and updates the DOM accordingly.

11. What is the purpose of keys in React lists?

Keys are used to uniquely identify elements in a list.

They help React efficiently update the list by associating elements with their previous state.

Keys should be stable, unique, and assigned to the top-level elements in a list.

// Example of using keys in a list
function MyList() {
      const items = ['Apple', 'Banana', 'Orange'];
      return (
        <ul>
          {items.map((item, index) => (
            <li key={index}>{item}</li>
          ))}
        </ul>
      );
    }

12. What is the purpose of the `componentDidMount` lifecycle method?

The `componentDidMount` method is called after a component is mounted (i.e., inserted into the DOM).

It is commonly used to perform side effects such as fetching data from an API or setting up event listeners.

// Example of using componentDidMount
class MyComponent extends React.Component {
      componentDidMount() {
        console.log('Component mounted');
      }
      render() {
        return <h1>Hello, World!</h1>;
      }
    }

13. What is the purpose of the `componentWillUnmount` lifecycle method?

The `componentWillUnmount` method is called just before a component is unmounted (i.e., removed from the DOM).

It is used to perform cleanup tasks such as cancelling timers or removing event listeners.

// Example of using componentWillUnmount
class Timer extends React.Component {
      constructor(props) {
        super(props);
        this.timerId = null;
      }
      componentDidMount() {
        this.timerId = setInterval(() => {
          console.log('Tick');
        }, 1000);
      }
      componentWillUnmount() {
        clearInterval(this.timerId);
      }
      render() {
        return <h1>Timer</h1>;
      }
    }

 14. What is the purpose of the `componentDidUpdate` lifecycle method?

The `componentDidUpdate` method is called after a component’s update is reflected in the DOM.

It is commonly used to perform side effects based on changes in the component’s props or state.

// Example of using componentDidUpdate
class Logger extends React.Component {
      componentDidUpdate(prevProps) {
        if (this.props.log !== prevProps.log) {
          console.log('Log updated:', this.props.log);
        }
      }
      render() {
        return <h1>Logger</h1>;
      }
    }

15. What is the purpose of the `shouldComponentUpdate` method?

The `shouldComponentUpdate` method is called before a component’s update.

It allows you to control whether the component should re-render or not based on the changes in its props or state.

By default, React re-renders a component whenever its props or state changes.

// Example of using shouldComponentUpdate
class MyComponent extends React.Component {
      shouldComponentUpdate(nextProps, nextState) {
        // Only re-render if the value changes
        return nextProps.value !== this.props.value;
      }
      render() {
        return <h1>{this.props.value}</h1>;
      }
    }

16. What is a controlled component in React?

A controlled component is a form element (like an input or textarea) whose value is controlled by React’s state. The value of the component is set by the state, and any changes to the value are handled by updating the state.

class MyForm extends React.Component {
      constructor(props) {
        super(props);
        this.state = { value: '' };
      }

      handleChange(event) {
        this.setState({ value: event.target.value });
      }
      render() {
        return (
          <input type="text" 
             value={this.state.value} 
             onChange={(event) => this.handleChange(event)}
          />
        );
      }
    }

17. What is an uncontrolled component in React?

    An uncontrolled component is a form element whose value is handled by the DOM rather than React’s state. The value is accessed using a ref and is not controlled by React.

// Example of an uncontrolled component
   function MyForm() {
      const inputRef = useRef();
      function handleSubmit(event) {
        event.preventDefault();
        console.log('Input value:', inputRef.current.value);
      }
      return (
        <form onSubmit={handleSubmit}>
          <input type="text" ref={inputRef} />
          <button type="submit">Submit</button>
        </form>
      );
    }

18. What is the purpose of the `useState` hook in React?

See also  JavaScript Object Methods With Examples

    The `useState` hook allows functional components to have state. It returns a state value and a function to update that value. The initial state is provided as an argument to the `useState` function.

    // Example of using useState
   function Counter() {
      const [count, setCount] = useState(0);
      function increment() {
        setCount(count + 1);
      }
      return (
        <div>
          <p>Count: {count}</p>
          <button onClick={increment}>Increment</button>
        </div>
      );
    }

19. What is the purpose of the `useEffect` hook in React?

The `useEffect` hook allows functional components to perform side effects.

It takes a callback function and runs it after every render. The effect can be cleaned up by returning a cleanup function from the callback.

// Example of using useEffect
function Logger() {
      useEffect(() => {
        console.log('Component rendered');
        return () => {
          console.log('Component unmounted');
        };
      });
      return <h1>Logger</h1>;
    }

20. What is the difference between `React.createElement` and JSX?

`React.createElement` is a function that creates React elements using a syntax similar to JSX.

JSX is a more concise and readable way to define React elements. JSX gets transpiled to `React.createElement` calls during the build process.

// Example using React.createElement
   const element = React.createElement('h1', null, 'Hello, World!');
 
    // Equivalent example using JSX
    const element = <h1>Hello, World!</h1>;

21. How can you pass props to a component in JSX?

    Props can be passed to a component in JSX using attributes. The attribute name represents the prop name, and the attribute value represents the prop value.

// Example of passing props to a component
   function Greeting(props) {
      return <h1>Hello, {props.name}!</h1>;
    }

    // Usage: <Greeting name="John" />

22. How can you conditionally render elements in JSX?

    You can use JavaScript expressions and conditional operators within JSX to conditionally render elements.

// Example of conditional rendering
   function Greeting(props) {
      return (
        <div>
          {props.isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>}
        </div>
      );
    }

23. What is the purpose of the `map` function in React?

    The `map` function is used to iterate over an array and transform its elements into React elements. It is commonly used to generate a list of elements based on an array of data.

// Example of using map
   function MyList() {
      const items = ['Apple', 'Banana', 'Orange'];
      return (
        <ul>
          {items.map((item) => (
            <li key={item}>{item}</li>
          ))}
        </ul>
      );
    }

24. What is the purpose of the `filter` function in React?

    The `filter` function is used to create a new array with elements that pass a given condition. In React, it can be used to filter data before rendering components.

// Example of using filter
   function MyList() {
      const items = ['Apple', 'Banana', 'Orange'];
      const filteredItems = items.filter((item) => item.startsWith('A'));
      return (
        <ul>
          {filteredItems.map((item) => (
            <li key={item}>{item}</li>
          ))}
        </ul>
      );
    }

25. How can you style components in React?

You can style components in React using CSS classes or inline styles. CSS classes can be applied using the `className` attribute, and inline styles can be specified using the `style` attribute.

// Example of styling a component
    function MyComponent() {

      return (

        <div className="my-component" style={{ color: 'red', fontSize: '16px' }}>

          Styled Component

        </div>

      );

    }

26. What are React Fragments and why are they used?

See also  Top 20 CSS Variables Interview Questions and Answers

React Fragments are used to group multiple elements together without adding an extra node to the DOM. They are useful when you want to return multiple elements from a component’s render method.

// Example of using React Fragments
    function MyComponent() {
      return (
        <>
          <h1>Title</h1>
          <p>Paragraph</p>
        </>
      );
    }

27. What is the purpose of the `key` prop in React lists?

The `key` prop is used to uniquely identify elements in a list. It helps React efficiently update the list by associating elements with their previous state.

Keys should be stable, unique, and assigned to the top-level elements in a list.

// Example of using keys in a list
function MyList() {
      const items = ['Apple', 'Banana', 'Orange'];
      return (
        <ul>
          {items.map((item, index) => (
            <li key={index}>{item}</li>
          ))}
        </ul>
      );
    }

28. What is the purpose of the `useRef` hook in React?

The `useRef` hook returns a mutable ref object whose `current` property can hold a value.

It can be used to reference elements or values that persist across component renders.

// Example of using useRef
    function MyComponent() {

      const inputRef = useRef();

      function focusInput() {
        inputRef.current.focus();
      }
      return (
        <>
          <input ref={inputRef} />
          <button onClick={focusInput}>Focus Input</button>
        </>
      );
    }

29. How can you handle forms in React?

Form handling in React involves managing form inputs using state and handling form submissions using event handlers.

You can capture the form input values in state and update them onChange, and handle the form submission in an onSubmit event handler.

// Example of handling a form in React
    class MyForm extends React.Component {

      constructor(props) {
        super(props);
        this.state = { username: '', password: '' };
      }

      handleChange(event) {
        this.setState({ [event.target.name]: event.target.value });
      }

      handleSubmit(event) {
        event.preventDefault();
        console.log('Username:', this.state.username);
        console.log('Password:', this.state.password);
      }

      render() {
        return (
          <form onSubmit={(event) => this.handleSubmit(event)}>
            <input
              type="text"
              name="username"
              value={this.state.username}
              onChange={(event) => this.handleChange(event)}
            />
            <input
              type="password"
              name="password"
              value={this.state.password}
              onChange={(event) => this.handleChange(event)}
            />
            <button type="submit">Submit</button>
          </form>
        );
      }
    }

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

Redux is a predictable state management library for JavaScript applications.

It provides a centralized store for managing application state and allows state changes to be predictable and traceable.

React applications can integrate with Redux to manage the state of their components.

// Example of using Redux with React
   import { createStore } from 'redux';

   import { Provider, connect } from 'react-redux';

    // Define a reducer function

    function counterReducer(state = 0, action) {
      switch (action.type) {
        case 'INCREMENT':
          return state + 1;
        case 'DECREMENT':
          return state - 1;
        default:
          return state;
      }
    }

    // Create a Redux store
    const store = createStore(counterReducer);

    // Define a React component
    function Counter({ count, increment, decrement }) {
      return (
        <div>
          <p>Count: {count}</p>
          <button onClick={increment}>Increment</button>
          <button onClick={decrement}>Decrement</button>
        </div>
      );
    }

    // Connect the component to the Redux store
    const mapStateToProps = (state) => ({
      count: state,
    });

    const mapDispatchToProps = (dispatch) => ({
      increment: () => dispatch({ type: 'INCREMENT' }),
      decrement: () => dispatch({ type: 'DECREMENT' }),
    });

    const ConnectedCounter = connect(mapStateToProps, mapDispatchToProps)(Counter);

    // Render the component wrapped with the Redux provider
    ReactDOM.render(
      <Provider store={store}>
        <ConnectedCounter />
      </Provider>,
      document.getElementById('root')
    );