React.js Interview Questions and Answers -part-2

React.js Interview Questions and Answers -part-2

·

8 min read

Interviewer: Can you explain what React is and why it’s widely used in modern web development?

Candidate: React is a JavaScript library developed by Facebook for building user interfaces, especially single-page applications. It allows developers to create reusable UI components, leading to faster and more maintainable code.

React is popular because of its:

  • Component-based architecture: Reusability of components simplifies development.

  • Virtual DOM: Improves performance by efficiently updating only the necessary parts of the DOM.

  • Unidirectional data flow: Ensures predictable state management.

  • Large ecosystem: Tools like Redux, React Router, and a vast community make it versatile.

Example:

import React from 'react';
function App() {
  return <h1>Hello, World!</h1>;
}
export default App;

Question 2: What are the differences between State and Props?

Interviewer: How do state and props differ in React?

Candidate:

  • State is a local data storage specific to a component. It can change over time and is used to manage the component’s behavior.

  • Props are read-only attributes passed from a parent component to a child component to configure or customize it.

Key Differences:

  • Mutability: State is mutable, props are immutable.

  • Scope: State is scoped to the component, while props are passed down from the parent.

Example:

function ChildComponent(props) {
  return <p>{props.message}</p>;
}

function ParentComponent() {
  return <ChildComponent message="Hello from Parent" />;
}

Question 3: What is the Virtual DOM?

Interviewer: Can you explain the Virtual DOM and its significance?

Candidate: The Virtual DOM is a lightweight JavaScript representation of the real DOM. When a component’s state or props change, React updates the Virtual DOM first, calculates the minimal set of changes required, and then applies those changes to the real DOM.

This process, known as reconciliation, enhances performance by avoiding costly direct manipulations of the real DOM.

Example:

// Before update
<div>Hello</div>

// After update
<div>Hello, World!</div>

React only updates the changed text node instead of re-rendering the entire div.

Question 4: What are React Hooks?

Interviewer: What are React Hooks, and why are they important?

Candidate: React Hooks are functions introduced in React 16.8 that allow developers to use state and other React features without writing class components.

Popular Hooks:

  • useState: For managing state.

  • useEffect: For handling side effects.

  • useContext: For accessing context.

Hooks make functional components more powerful and simplify code structure.

Example:

import React, { useState } from 'react';

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

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

Question 5: What is the difference between controlled and uncontrolled components?

Interviewer: Can you differentiate between controlled and uncontrolled components in React?

Candidate:

  • Controlled Components: The form data is handled by the React component’s state.

  • Uncontrolled Components: The form data is handled by the DOM itself using ref.

Example of Controlled Component:

function ControlledInput() {
  const [value, setValue] = useState('');

  return (
    <input type="text" value={value} onChange={(e) => setValue(e.target.value)} />
  );
}

Example of Uncontrolled Component:

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

  const handleSubmit = () => {
    alert(inputRef.current.value);
  };

  return (
    <>
      <input type="text" ref={inputRef} />
      <button onClick={handleSubmit}>Submit</button>
    </>
  );
}

Question 6: Explain the concept of lifting state up.

Interviewer: What is lifting state up in React?

Candidate: Lifting state up refers to moving the state from a child component to a common parent component. This approach allows multiple child components to share and synchronize data through the parent.

Example:

function Parent() {
  const [value, setValue] = useState('');

  return (
    <>
      <ChildA value={value} />
      <ChildB onChange={setValue} />
    </>
  );
}

function ChildA({ value }) {
  return <p>Value: {value}</p>;
}

function ChildB({ onChange }) {
  return <input onChange={(e) => onChange(e.target.value)} />;
}

Question 7: What are error boundaries in React?

Interviewer: How do error boundaries work in React?

Candidate: Error boundaries are React components that catch JavaScript errors in their child component tree, log the errors, and display a fallback UI instead of crashing the application.

Implementation:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}

Usage:

<ErrorBoundary>
  <MyComponent />
</ErrorBoundary>

Question 8: How can you optimize the performance of a React application?

Interviewer: What techniques would you use to optimize a React app?

Candidate:

  1. Using React.memo: Prevents unnecessary re-renders of functional components.

  2. Lazy Loading: Loads components and resources only when needed.

  3. Code Splitting: Splits the app into smaller bundles.

  4. Use PureComponent: Avoids re-rendering if props and state are unchanged.

  5. Optimizing State: Keeping the state localized.

  6. Avoiding Anonymous Functions in JSX: Improves performance by preventing re-creation of functions.

Example:

const MemoizedComponent = React.memo(MyComponent);

Question 9: What is the purpose of useEffect in React?

Interviewer: How does the useEffect hook work in React?

Candidate: The useEffect hook is used to handle side effects in functional components, such as data fetching, subscriptions, and DOM manipulations. It replaces lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.

Example:

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

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

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []); // Empty dependency array means it runs once when the component mounts

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

Question 10: What are Higher-Order Components (HOCs)?

Interviewer: Can you explain Higher-Order Components in React?

Candidate: A Higher-Order Component (HOC) is a function that takes a component and returns a new component, enhancing it with additional functionality.

Example:

function withLoading(Component) {
  return function WrappedComponent({ isLoading, ...props }) {
    if (isLoading) return <p>Loading...</p>;
    return <Component {...props} />;
  };
}

function DataDisplay({ data }) {
  return <p>{data}</p>;
}

const EnhancedComponent = withLoading(DataDisplay);

Question 11: What is React Context, and when would you use it?

Interviewer: How does React Context help in state management?

Candidate: React Context provides a way to share values between components without passing props through every level of the tree. It's useful for global state like theme, user authentication, and language settings.

Example:

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

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

function Toolbar() {
  return <ThemedButton />;
}

function ThemedButton() {
  const theme = React.useContext(ThemeContext);
  return <button className={theme}>Theme is {theme}</button>;
}

Question 12: What are Higher-Order Components (HOCs) in React?

Interviewer: Can you explain what Higher-Order Components are and provide an example?

Candidate: A Higher-Order Component (HOC) is a pattern in React where a function takes a component as an argument and returns a new component. HOCs are used for reusing component logic and adding additional behavior to components.

Key Characteristics:

  • HOCs don’t modify the original component.

  • They wrap the original component with additional functionality.

Example:

function withLogging(WrappedComponent) {
  return function EnhancedComponent(props) {
    useEffect(() => {
      console.log('Component Mounted');
      return () => console.log('Component Unmounted');
    }, []);

    return <WrappedComponent {...props} />;
  };
}

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

const MyComponentWithLogging = withLogging(MyComponent);

In this example, withLogging adds logging functionality to MyComponent.


Question 13: What is React's Context API, and when should you use it?

Interviewer: How does the Context API work, and in what scenarios would you use it?

Candidate: The Context API provides a way to share data between components without passing props through every level of the component tree. It’s useful for managing global state like user authentication, themes, or language settings.

Steps to Use Context API:

  1. Create Context:
const ThemeContext = React.createContext();
  1. Provide Context Value:
function App() {
  return (
    <ThemeContext.Provider value={{ theme: 'dark' }}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}
  1. Consume Context Value:
function Toolbar() {
  const { theme } = useContext(ThemeContext);
  return <div>The current theme is {theme}</div>;
}

Question 14: What is the difference between React Router's BrowserRouter and HashRouter?

Interviewer: Can you explain the difference between BrowserRouter and HashRouter?

Candidate:

  • BrowserRouter: Uses the HTML5 history API to keep the UI in sync with the URL. It provides clean URLs without the hash symbol (e.g., example.com/about).

  • HashRouter: Uses the hash portion of the URL to track the current route (e.g., example.com/#/about).

Key Differences:

  • URL Structure: BrowserRouter has cleaner URLs, while HashRouter includes a hash (#).

  • Compatibility: HashRouter works well with older browsers and static file servers that don’t support client-side routing.

  • Use Case: BrowserRouter is preferred for modern apps; HashRouter is used for simpler setups or when server configuration isn’t possible.

Example:

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

function App() {
  return (
    <BrowserRouter>
      <Route path="/about" component={About} />
    </BrowserRouter>
  );
}

Question 15: What is server-side rendering (SSR) in React, and what are its benefits?

Interviewer: Could you explain server-side rendering and why it might be used?

Candidate: Server-side rendering (SSR) is the process of rendering React components on the server and sending the fully rendered HTML to the client. This contrasts with client-side rendering, where the browser renders components after downloading JavaScript.

Benefits of SSR:

  1. Improved SEO: Search engines can easily crawl fully-rendered pages.

  2. Faster Time to First Paint (TTFP): Users see content sooner since the HTML is pre-rendered.

  3. Better Performance on Low-end Devices: Reduces the work required on the client-side.

Example with Next.js:

import React from 'react';

export async function getServerSideProps() {
  const data = await fetch('https://api.example.com/data').then(res => res.json());
  return { props: { data } };
}

function Page({ data }) {
  return <div>Data: {data.message}</div>;
}

export default Page;

In this example, getServerSideProps fetches data at request time, and the page is pre-rendered on the server.

Connect with me

If you have any questions about my projects or want to discuss potential collaboration opportunities, please don't hesitate to connect with me. You can reach me through the following channels:

Email:

LinkedIn: linkedin.com/in/bodheeshvc

GitHub: github.com/BODHEESH

Youtube: youtube.com/@BodhiTechTalks

Medium: medium.com/@bodheeshvc.developer

Twitter: x.com/Bodheesh_

I'm always happy to connect with other professionals in the tech industry and discuss ways to work together. Feel free to reach out and let's see how we can help each other grow and succeed!