1. What is React?

Answer:
React is an open-source JavaScript library developed by Facebook, which allow us to create a user interfaces for web application especially for single page application. This allows developers to build reusable UI components and manage the state of the application efficiently. The react uses a virtual DOM that needs to improve the performance by updating only parts of UI instead of re -loading the entire page.


2. What are the key features of React?

Answer:

JSX (JavaScript XML): JSX allows you to write HTML in JavaScript, making it easier to define UI components.

Components: React is component-based, meaning UIs are broken down into reusable building blocks. Each component manages its own state and logic, making your code more organized, maintainable, and scalable. (functional or class components).

Virtual DOM: React uses a Virtual DOM, which is a lightweight copy of the actual DOM. When state changes occur, React first updates the Virtual DOM, then efficiently compares it with the real DOM to make the smallest necessary changes. This boosts performance and ensures a fast user experience.

State and Props:
State: Each component can have its own state, which determines its behavior or appearance. When the state changes, React automatically re-renders the component.

– Props: Props (short for properties) are used to pass data from a parent component to a child component. They are immutable, meaning the child cannot change the props directly.

React Router: React Router helps in handling navigation and routing in React applications, making it easy to switch between different views or pages without reloading the entire page.

Hooks: React Hooks (like useState, useEffect, etc.) allow you to manage state and side effects in functional components. This provides a simpler and cleaner alternative to class components.

Performance Optimization: React optimizes rendering through its Virtual DOM, where it performs a “diffing” algorithm to update only the changed parts of the UI.


3. What is JSX, and how does it differ from regular JavaScript?

Answer:
JSX is a syntax extension for JavaScript that allows you to write HTML-like code within JavaScript. It makes it easier to visualize and write UI elements directly inside JavaScript functions. While it looks similar to HTML, it’s actually syntactic sugar that gets transpiled into JavaScript by tools like Babel.

Example:

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

The main difference is that JSX requires expressions to be wrapped in curly braces {}, whereas regular JavaScript would use standard HTML or JavaScript syntax.


4. What are props in React?

Answer:
Props (short for “properties”) are read-only objects that are passed from a parent component to a child component. They allow data to flow from one component to another and are used to configure or customize the child component.

Example:


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

<Greeting name="John" />

Here, name is a prop passed to the Greeting component.


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

Answer:

State: State is a mutable object that belongs to a component and can be modified within that component. Changes to state cause the component to re-render.

Props: Props are immutable and are used to pass data from a parent component to a child component. They cannot be modified by the receiving component.

Example:


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>
);
}
}

In this example, state holds the count value, while props would be used to pass data to child components.

6. What are React Hooks?

Answer:
React Hooks are functions that allow you to use state and other React features in functional components. Before hooks, only class components could manage state, but hooks introduced a way to manage state and lifecycle methods in functional components.

Common hooks include:

  • useState: Manages local component state.
  • useEffect: Executes side effects like data fetching or DOM manipulation.
  • useContext: Accesses context values.
  • useRef: Provides a reference to a DOM element or a mutable value that persists between renders.

Example of useState:


import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

7. What is the virtual DOM in React?

Answer:
The virtual DOM is an in-memory representation of the actual DOM. React maintains this virtual DOM to optimize updates to the real DOM. When the state of a component changes, React first updates the virtual DOM, compares it with the previous version, and only updates the parts of the actual DOM that have changed. This process is known as “reconciliation” and helps improve performance.


8. What is the purpose of useEffect?

Answer:
useEffect is a React hook that runs side effects in functional components. Side effects include operations like data fetching, manual DOM manipulation, or setting up subscriptions. It is called after the render cycle, allowing you to perform actions without blocking the render.

Example:


import { useState, useEffect } from 'react';

function App() {
  const [data, setData] = useState(null);

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

  return <div>{data ? <p>{data}</p> : <p>Loading...</p>}</div>;
}

In this example, useEffect is used to fetch data after the component mounts.


9. What is conditional rendering in React?

Answer:
Conditional rendering allows you to render different UI components or elements based on certain conditions. In React, this is done using JavaScript expressions like if, ternary operators, or && (AND) operators.

Example:


function Welcome({ isLoggedIn }) {
  return (
    <div>
      {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>}
    </div>
  );
}

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

Answer:
A higher-order component (HOC) is a function that takes a component and returns a new component with additional props or functionality. HOCs are commonly used for cross-cutting concerns like authentication, logging, or data fetching.

Example:


function withLoading(Component) {
  return function WithLoading(props) {
    if (props.isLoading) {
      return <div>Loading...</div>;
    }
    return <Component {...props} />;
  };
}

const EnhancedComponent = withLoading(MyComponent);

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

Answer:
Redux is a state management library for JavaScript applications. It helps manage global state in applications, allowing components to access and update state in a predictable way. React and Redux can be integrated using the react-redux library, which provides hooks like useSelector and useDispatch to connect React components with the Redux store.

12. What is the difference between React and Angular?

Answer:
React is a JavaScript library used for building user interfaces, while Angular is a complete framework for building web applications. React focuses on the view layer (UI) and is more flexible in terms of integration, whereas Angular provides a full set of tools (like routing, forms, HTTP services, etc.) to build complete applications.


13. What is a component in React?

Answer:
A component in React is a reusable, self-contained building block that represents a part of the UI. Components can either be class components (using ES6 class syntax) or functional components (using functions). Components can accept props and maintain state.


14. What are the differences between functional and class components?

Answer:

Functional Components: Simpler components that are defined using functions. They can use hooks like useState, useEffect, etc., to manage state and lifecycle methods.

Class Components: Older React components defined using ES6 classes. They have a built-in state object and lifecycle methods such as componentDidMount and render.

Since React 16.8, functional components with hooks have become the preferred way to write components.


15. What is a key in React, and why is it important?

Answer:
A key is a special string attribute used to identify components in a list or array. Keys help React identify which items have changed, added, or removed, making the re-rendering process more efficient.

Example:


const items = ['Apple', 'Banana', 'Cherry'];

function List() {
  return (
    <ul>
      {items.map((item, index) => (
        <li key={index}>{item}</li>
      ))}
    </ul>
  );
}

16. What is the difference between state and this.setState?

Answer:

state: Represents the current state of a component. It holds information that can change over time, causing the component to re-render.

this.setState: A method used in class components to update the state. When setState is called, React schedules a re-render with the new state.

Example:


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>{this.state.count}</p>
        <button onClick={this.increment}>Increment</button>
      </div>
    );
  }
}

17. What are React lifecycle methods?

Answer:
Lifecycle methods are special methods in class components that allow you to hook into different stages of a component’s life, such as when it is mounted, updated, or unmounted. Some common lifecycle methods include:

componentDidMount: Called after the component is rendered to the screen.

componentDidUpdate: Called after the component updates.

componentWillUnmount: Called before the component is removed from the DOM.

In functional components, the equivalent functionality is provided by the useEffect hook.


18. What is the render method in React?

Answer:
The render method is required in class components and is responsible for returning the JSX that represents the UI. It returns a React element, which will be rendered to the DOM.

Example:


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

19. What is the difference between a controlled and an uncontrolled component?

Answer:

Controlled Component: A component whose form data is handled by React state. The input elements’ values are controlled by the state, making it easier to manage and validate data.

Example:


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


Uncontrolled Component: A component that maintains its own internal state. You access the value using a reference (ref), and React doesn’t directly manage the form input.

Example:


function UncontrolledInput() {
  const inputRef = useRef(null);

  const handleSubmit = () => {
    alert(`Input value is: ${inputRef.current.value}`);
  };

  return <input ref={inputRef} />;
}

20. What is the useRef hook used for in React?

Answer:
The useRef hook is used to persist values across renders without causing re-rendering. It is often used for accessing DOM elements or storing mutable values that don’t trigger a re-render when updated.

Example:


function FocusInput() {
  const inputRef = useRef();

  const handleFocus = () => {
    inputRef.current.focus();
  };

  return (
    <>
      <input ref={inputRef} />
      <button onClick={handleFocus}>Focus the input</button>
    </>
  );
}

21. What is prop drilling?

Answer:
Prop drilling refers to the process of passing data through multiple layers of components by using props, even if the intermediate components don’t need the data. This can be inefficient in large applications and often leads to the use of Context API or state management libraries like Redux.


22. What is the Context API in React?

Answer:
The Context API in React is a way to pass data through the component tree without having to pass props down manually at every level. It is useful for managing global state such as authentication data, themes, or language preferences.

Example:


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

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Component />
    </ThemeContext.Provider>
  );
}

function Component() {
  const theme = useContext(ThemeContext);
  return <div>{theme}</div>;
}