React Interview Questions and Answers

author image Hirely
at 08 Jan, 2025

Question: What is React Router and how does it work?

Answer:

React Router is a popular library for managing routing in React applications. It allows you to define multiple routes in your app and enables navigation between different components or views without reloading the page. React Router helps in building single-page applications (SPA) by managing the history of URL changes and rendering the correct components based on the URL.

How React Router Works:

React Router works by listening to changes in the browser’s URL and rendering the appropriate components based on the path. It uses the browser’s history API to manage navigation and does not cause a full page reload, which is typical in traditional web applications. Instead, React Router dynamically updates the UI based on the URL.

React Router is primarily composed of the following key components:

  1. Router: Manages the history of the navigation and tracks the current location.
  2. Route: Defines which component to render when the URL matches a specific pattern.
  3. Link: Creates navigable links within your application that trigger route changes.
  4. Switch: Ensures that only the first matching route is rendered.
  5. History: Provides control over the navigation history (push, replace, and go back).

Key Features of React Router:

  1. Declarative Routing: You define routing rules in the JSX markup using <Route> components.
  2. Dynamic Routing: Routes can change based on user input or any other application state, which allows for flexible UI rendering.
  3. Nested Routes: React Router allows for nesting routes to create a hierarchy of components that match different URL paths.
  4. Programmatic Navigation: React Router also enables programmatic navigation, meaning you can change the route based on actions in your application (e.g., button click or form submission).
  5. Path Matching: React Router can handle dynamic URL parameters (like /user/:id) to display different content based on the route parameters.
  6. History API: React Router integrates with the browser’s history API to manage history without reloading the page, enabling the back and forward buttons to work as expected.

Example of How React Router Works:

Step 1: Install React Router

First, you need to install react-router-dom (for web applications):

npm install react-router-dom

Step 2: Basic Setup with React Router

Here is an example of how to set up routing with React Router:

import React from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';

// Define components to be rendered for each route
const Home = () => <h2>Home Page</h2>;
const About = () => <h2>About Page</h2>;
const Contact = () => <h2>Contact Page</h2>;

// App component
const App = () => {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
            <li>
              <Link to="/contact">Contact</Link>
            </li>
          </ul>
        </nav>

        {/* Switch renders the first matching Route */}
        <Switch>
          <Route path="/" exact component={Home} />
          <Route path="/about" component={About} />
          <Route path="/contact" component={Contact} />
        </Switch>
      </div>
    </Router>
  );
};

export default App;

Explanation:

  1. <Router>: The BrowserRouter component (aliased as Router) is used to keep the UI in sync with the URL. It uses the browser’s history API for navigation.
  2. <Route>: Defines the routes in the application. The path prop is used to match the URL and determine which component should be rendered. The exact prop is used to ensure that the route matches the exact path (without it, it would match any path that starts with /).
  3. <Link>: The Link component is used to create navigation links to different routes within your app. It works similarly to an anchor tag (<a>), but it doesn’t reload the page.
  4. <Switch>: This component ensures that only the first matching <Route> is rendered. Without Switch, multiple routes might match the same path, and all of them could render.

Step 3: Dynamic Routing (with URL Parameters)

You can use dynamic routes to pass parameters via the URL, which can be accessed by the component that is rendered.

Example of a dynamic route:

import React from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';

const UserProfile = ({ match }) => {
  return <h2>User Profile of {match.params.username}</h2>;
};

const App = () => {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/user/john">John's Profile</Link>
            </li>
            <li>
              <Link to="/user/jane">Jane's Profile</Link>
            </li>
          </ul>
        </nav>

        <Switch>
          <Route path="/user/:username" component={UserProfile} />
        </Switch>
      </div>
    </Router>
  );
};

export default App;

In this example, :username is a dynamic parameter in the URL. React Router will match this URL and pass the username parameter to the UserProfile component.

Step 4: Programmatic Navigation

You can navigate programmatically using useHistory (in React Router v5) or useNavigate (in React Router v6).

Example using useNavigate in React Router v6:

import React from 'react';
import { useNavigate } from 'react-router-dom';

const NavigateButton = () => {
  const navigate = useNavigate();

  const handleClick = () => {
    // Navigate programmatically to another route
    navigate('/about');
  };

  return <button onClick={handleClick}>Go to About Page</button>;
};

export default NavigateButton;

Step 5: Nested Routes

React Router supports nested routes, which allow you to render a route inside another route.

Example of nested routes:

import React from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';

const Home = () => (
  <div>
    <h2>Home Page</h2>
    <ul>
      <li><Link to="/home/subpage1">Subpage 1</Link></li>
      <li><Link to="/home/subpage2">Subpage 2</Link></li>
    </ul>
  </div>
);

const Subpage1 = () => <h3>Subpage 1</h3>;
const Subpage2 = () => <h3>Subpage 2</h3>;

const App = () => {
  return (
    <Router>
      <Switch>
        <Route path="/home" exact component={Home} />
        <Route path="/home/subpage1" component={Subpage1} />
        <Route path="/home/subpage2" component={Subpage2} />
      </Switch>
    </Router>
  );
};

export default App;

In this case, the Home component contains links to nested routes (/home/subpage1 and /home/subpage2), and React Router will render the corresponding components when the URL matches.

Summary of Key React Router Components:

  1. Router: The container that keeps track of history and renders the UI accordingly.
  2. Route: Defines a mapping between the URL and the component to render.
  3. Link: Used to create navigation links without reloading the page.
  4. Switch: Renders only the first matching route.
  5. useNavigate (React Router v6) / useHistory (React Router v5): Allows programmatic navigation.

Conclusion:

React Router is an essential library for building single-page applications in React. It provides a powerful set of tools for managing routes, handling navigation, and rendering the appropriate components based on the URL. It supports features like dynamic routing, nested routes, programmatic navigation, and more, allowing you to create rich, dynamic web applications.

Question: What is Redux and how is it used in React?

Answer:

Redux is a predictable state container for JavaScript applications. It is often used with React to manage the state of an application in a centralized store. Redux follows three core principles:

  1. Single Source of Truth: The entire state of your application is stored in a single object, called the “store”. This makes it easier to manage and debug the application’s state.

  2. State is Read-Only: The only way to change the state is by dispatching an action, which is a plain JavaScript object describing what happened in the application.

  3. Changes are Made with Pure Functions: To specify how the state changes in response to actions, you write pure functions called “reducers”. These reducers take the current state and an action, and return a new state.

How Redux is Used in React:

  1. Store: You create a Redux store to hold the state of your application. The store is the central place where your state is kept.

  2. Actions: Actions are plain JavaScript objects that describe “what happened”. For example, when a user clicks a button, an action is dispatched to indicate that an event has occurred.

  3. Reducers: Reducers are functions that specify how the state changes in response to actions. They take the current state and an action as arguments, and return the new state.

  4. Dispatch: When an action is triggered (e.g., a user clicks a button or submits a form), the action is sent to the Redux store via dispatch(). This will call the reducer to update the state.

  5. Connecting Redux with React: React-Redux is the library that binds Redux with React. The Provider component from react-redux makes the Redux store available to the rest of the app, and the connect function (or useSelector and useDispatch hooks in modern React) allows React components to read from the store and dispatch actions.

Example Usage in React:

// Action
const increment = () => ({ type: 'INCREMENT' });

// Reducer
const counterReducer = (state = 0, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    default:
      return state;
  }
};

// Store
import { createStore } from 'redux';
const store = createStore(counterReducer);

// Component
import { useSelector, useDispatch } from 'react-redux';

const Counter = () => {
  const count = useSelector(state => state); // Accessing the state
  const dispatch = useDispatch();

  return (
    <div>
      <p>{count}</p>
      <button onClick={() => dispatch(increment())}>Increment</button>
    </div>
  );
};

// Provider to make store available to components
import { Provider } from 'react-redux';

const App = () => (
  <Provider store={store}>
    <Counter />
  </Provider>
);

Why Use Redux with React?

  • Centralized State: It provides a global state management solution that can be accessed by any component.
  • Predictable State Changes: Redux ensures that state changes are predictable and follow a clear structure.
  • Debugging Tools: Tools like Redux DevTools allow developers to track actions, state changes, and time travel debugging, making it easier to debug complex state logic.
  • Consistency: Redux helps manage complex applications where state needs to be shared or passed down through multiple components.

However, Redux can introduce boilerplate code and complexity, so it’s most beneficial in larger applications where state management is complex. For smaller apps, the built-in React state (useState) or Context API might suffice.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as ReactJS interview questions, ReactJS interview experiences, and details about various ReactJS job positions. Click here to check it out.

Related Posts

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now