React interview Questions with examples

1. What is React?

Ans. React is a JavaScript library developed by Facebook for building user interfaces, specifically for single-page applications (SPAs) where user interactions update the view without a page reload. It emphasizes reusable components, where each component manages its own state and can be composed to form complex UIs.

import React from 'react';

const Hello = () => <h1>Hello, World!</h1>;
export default Hello;

This component returns a simple greeting, “Hello, World!”. Hello is a reusable, independent piece of UI in the application.

2. What is JSX?

Ans: JSX (JavaScript XML) is a syntax extension that lets you write HTML-like code in JavaScript, making it easier to visualize UIs in React. JSX is transformed to React.createElement calls by tools like Babel.

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

JSX here is the <h1>Hello, JSX!</h1>. It looks like HTML, but it’s JavaScript and will render an h1 header.

3. What are components in React?

Ans: Components are the core building blocks of React applications. They are reusable and encapsulate structure, logic, and styling. Components can be functional (using functions) or class-based (using ES6 classes).

function Greeting() {
  return <h1>Hello!</h1>;
}
export default Greeting;

This Greeting component is a functional component that displays a heading with the text “Hello!”. It’s reusable across the app.

4. What is the virtual DOM?

Ans: The virtual DOM is a lightweight copy of the actual DOM. React updates the virtual DOM first, then compares it with a previous copy (a process called “diffing”) to determine the minimal set of changes needed to update the real DOM efficiently.

5. How does React’s reconciliation process work?

Ans: React compares the old and new virtual DOMs to identify changes and updates only those parts of the real DOM that have changed, which makes rendering efficient and fast.

6. What is the difference between state and props?

Ans:

  • State is data managed within a component that can change over time.
  • Props are inputs to a component, passed from a parent component, and are read-only.
const Child = (props) => <h1>{props.message}</h1>;

const Parent = () => {
  return <Child message="Hello from Parent!" />;
};

Here, message is a prop passed from Parent to Child, displaying “Hello from Parent!”.

7. How do you update the state in a functional component?

Ans: In functional components, useState is used to create and update state.

Example:

import React, { useState } from 'react';

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

The Counter component maintains a count state. setCount updates it whenever the button is clicked.

8. What are hooks in React?

Ans: Hooks are functions that let you use React features like state and lifecycle methods in functional components. Common hooks include useState, useEffect, and useContext.

9. Explain useEffect.

Ans: useEffect is a hook that lets you run side effects (like data fetching, subscriptions, and timers) in functional components. It runs after every render by default, or only when specified dependencies change.

Example:

import React, { useEffect, useState } from 'react';

const DataFetcher = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []);  // Empty dependency array ensures this only runs once on mount.

  return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
};

This component fetches data from an API once on mount.

10. What is the context API?

Ans: The context API is used to create global variables in React, allowing values to be shared without passing props through each component layer.

Example:

import React, { useContext } from 'react';

const ThemeContext = React.createContext('light');

const ThemedComponent = () => {
  const theme = useContext(ThemeContext);
  return <div>Theme: {theme}</div>;
};

Here, ThemedComponent accesses the theme value from ThemeContext directly, bypassing intermediate components.

11. What is Redux?

Ans: Redux is a library for managing and centralizing application state. It provides a predictable state container, making it easier to manage complex state across the application.

12. How does useSelector work in Redux with React?

Ans: useSelector is a hook that lets you extract data from the Redux store state in a React component.

Example:

import { useSelector } from 'react-redux';

const CounterDisplay = () => {
  const count = useSelector(state => state.count);
  return <div>Count: {count}</div>;
};

This component displays the count value from the Redux store.

13. Explain useDispatch in Redux.

Ans: useDispatch is a hook that provides access to the Redux dispatch function, allowing you to send actions to update the store.

Example:

import { useDispatch } from 'react-redux';

const IncrementButton = () => {
  const dispatch = useDispatch();
  return <button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>;
};

The button dispatches an INCREMENT action to update the state in the Redux store.

14. What is a higher-order component (HOC)?

Ans: An HOC is a function that takes a component and returns a new component with added props or behaviors, enhancing the original component.

Example:

const withLogging = (Component) => (props) => {
  console.log('Rendering component with props:', props);
  return <Component {...props} />;
};

const Hello = (props) => <h1>Hello, {props.name}!</h1>;
export default withLogging(Hello);

Here, withLogging logs props each time the wrapped Hello component renders.

15. How does React Router work?

Ans: React Router is a library for adding navigation and routing to React applications.

Example:

import { BrowserRouter, Route, Link } from 'react-router-dom';

const Home = () => <h2>Home</h2>;
const About = () => <h2>About</h2>;

const App = () => (
  <BrowserRouter>
    <nav>
      <Link to="/">Home</Link>
      <Link to="/about">About</Link>
    </nav>
    <Route path="/" exact component={Home} />
    <Route path="/about" component={About} />
  </BrowserRouter>
);

This setup provides routes for the Home and About pages with navigation links.

16. What are controlled and uncontrolled components?

Ans:

  • Controlled Components: Form elements managed by React state.
  • Uncontrolled Components: Form elements where the DOM manages their state.

Example :

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

The value of ControlledInput is controlled by the React state.

17. What is React.Fragment?

Ans: React.Fragment allows grouping multiple elements without adding extra nodes to the DOM.

Example:

return (
  <React.Fragment>
    <h1>Title</h1>
    <p>Content</p>
  </React.Fragment>
);

Using React.Fragment, h1 and p are grouped without an extra div.

18. What are keys in React, and why are they important?

Ans: Keys help React identify list items and efficiently update or re-order them.

Example:

const items = ["Apple", "Banana", "Cherry"];
const list = items.map((item, index) => <li key={index}>{item}</li>);

Here, each list item has a unique key, helping React track and update items efficiently.

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

Ans: Prop drilling is passing props through multiple components to reach a deeply nested component. It can be avoided with the Context API.

Example:

const UserContext = React.createContext();

By wrapping components in UserContext, deeply nested components can access values without prop drilling.

20. How does memo work in React?

Ans: React.memo is a higher-order component that optimizes re-renders by memoizing a component.

Example:

const MyComponent = React.memo(({ count }) => <p>{count}</p>);

MyComponent only re-renders if the count prop changes, improving performance

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *