React Coding Interview Questions & Solutions 2024, Get React Interview Questions

React Coding Interview Questions & Solutions 2024 | React Coding Interview Questions | React Interview Questions | React Coding Interview Questions and Answers 

React Coding Interview Questions & Solutions 2024: The Coding test is containing many programming languages. This Coding Test Round is evaluating your programming Skills and Coding Knowledge. The selection process contains many levels of the test. Coding Test is one of the main difficulty parts in every private sector interviews. Every Candidates mainly focused on this Coding Test. In the Private Sector Company of React is hiring eligible employees. Many of the eligible candidates are applied in the React Careers 2024. The Juspay will conducting the hiring test for each post. Here we provided the Common React Coding Questions and Answers/ React Coding Interview Questions. Who are interested in the React Hiring, they definitely prepare for the selection process. The hiring process is containing Coding Interview Round. React will mostly ask the React Coding questions in the C, C++, Java, Python Program. Candidates thoroughly prepare for the Languages for React Coding Interview process.

By solving the React Coding Interview Questions and Answers, you will clear the Coding Interview Round. Candidates must prepare for the React Coding test. In this page you can get the React Coding questions 2024, React Coding Interview questions, React Coding Question and Answers etc.,
React Coding Interview Questions and Answers 

Q) Implement Search Functionality

Fetch the user details and display user names. Also, implement a search bar functionality on the username.

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

const UserList = () => {
  const [users, setUsers] = useState([]);
  const [searchTerm, setSearchTerm] = useState('');

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users') // Fetching user details from the given endpoint
      .then(response => response.json())
      .then(data => setUsers(data))
      .catch(error => console.error('Error fetching user data:', error));
  }, []);

  const filteredUsers = users.filter(user =>
    user.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div>
      <h2>User List</h2>
      <input
        type="text"
        placeholder="Search by username"
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      <ul>
        {filteredUsers.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default UserList;

Q) Implement Sort By Username Functionality

Write code to fetch the user’s details and display the usernames. There should be two buttons to sort usernames in ascending order and descending order.

import { useState, useEffect } from "react";

const App = () => {
  const [usersData, setUsersData] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((res) => res.json())
      .then((data) => {
        setUsersData(data);
      })
      .catch((error) => {
        throw error;
      });
  }, []);

  const handleAscendingSort = () => {
    const users = [...usersData].sort((a, b) =>
      a.username.localeCompare(b.username)
    );
    setUsersData(users);
  };

  const handleDescendingSort = () => {
    const users = [...usersData].sort((a, b) =>
      b.username.localeCompare(a.username)
    );
    setUsersData(users);
  };

  return (
    <div className="App">
      <h1>Example of short by username</h1>
      <button onClick={() => handleAscendingSort()}>
        Short by Ascending
      </button>
      <button onClick={() => handleDescendingSort()}>
        Short by Descending
      </button>
      {usersData &&
        usersData.map((user) => (
          <div key={user.id}>
            <p>{user.username}</p>
          </div>
        ))}
    </div>
  );
}

export default App;

Q) Dark and Light Mode

Implement the logic to change the app display mode using context API.

-DisplayModeContext.js file

import React, { createContext, useState, useContext } from “react”;

// Create a context for the display mode
const DisplayModeContext = createContext();

// Create a custom hook to use the display mode context
export const useDisplayMode = () => {
return useContext(DisplayModeContext);
};

// Create a provider component for the display mode context
export const DisplayModeProvider = ({ children }) => {
const [displayMode, setDisplayMode] = useState(“light”); // Default display mode is ‘light’

const toggleDisplayMode = () => {
setDisplayMode((prevMode) => (prevMode === “light” ? “dark” : “light”)); // Toggle between ‘light’ and ‘dark’ mode
};

return (
<DisplayModeContext.Provider value={{ displayMode, toggleDisplayMode }}>
{children}
</DisplayModeContext.Provider>
);
};

-App.js file

import “./styles.css”;
import { useDisplayMode } from “./DisplayModeContext”;

export default function App() {
const { displayMode, toggleDisplayMode } = useDisplayMode();

const appStyle = {
background: displayMode === “light” ? “#ffffff” : “#333333”,
color: displayMode === “light” ? “#333333” : “#ffffff”,
padding: “5px”,
};

return (
<div style={appStyle}>
<h3>Press below button to change the display mode</h3>
<button onClick={() => toggleDisplayMode()}>
{displayMode === “light” ? “Dark Mode” : “Light Mode”}
</button>
</div>
);
}

-index.js

import { StrictMode } from “react”;
import { createRoot } from “react-dom/client”;

import App from “./App”;
import { DisplayModeProvider } from “./DisplayModeContext”;

const rootElement = document.getElementById(“root”);
const root = createRoot(rootElement);

root.render(
<StrictMode>
<DisplayModeProvider>
<App />
</DisplayModeProvider>
</StrictMode>
);

Q) Shopping Cart Component

Prepare JSON data for shopping items and implement a shopping cart app where users can add items, update the number of items, remove items, and display the final amount for the total order.

-items.json

// items.json
{
“items”: [
{
“id”: 1,
“name”: “T-shirt”,
“price”: 20
},
{
“id”: 2,
“name”: “Jeans”,
“price”: 50
},
{
“id”: 3,
“name”: “Shoes”,
“price”: 80
}
]
}

-App.js

import { useState } from “react”;
import “./styles.css”;
import itemsData from “./items.json”;

export default function App() {
const [items, setItems] = useState(itemsData.items);
const [cart, setCart] = useState([]);

const addToCart = (itemId) => {
const selectedItem = items.find((item) => item.id === itemId);
const itemInCart = cart.find((item) => item.id === itemId);

if (itemInCart) {
const updatedCart = cart.map((item) => {
if (item.id === itemId) {
return { …item, quantity: (item.quantity || 1) + 1 };
}
return item;
});
setCart(updatedCart);
} else {
setCart([…cart, { …selectedItem, quantity: 1 }]);
}
};

const removeFromCart = (itemId) => {
const updatedCart = cart.filter((item) => item.id !== itemId);
setCart(updatedCart);
};

const updateQuantity = (itemId, newQuantity) => {
if (newQuantity > 5) {
return; // Prevent updating quantity beyond 5
}
const updatedCart = cart.map((item) => {
if (item.id === itemId) {
return { …item, quantity: newQuantity };
}
return item;
});
setCart(updatedCart);
};

const calculateTotal = () => {
return cart.reduce(
(total, item) => total + item.price * (item.quantity || 1),
0
);
};

return (
<div>
<h1>Shopping Cart</h1>
<h2>Available Items</h2>
<ul>
{items.map((item) => (
<li key={item.id}>
{item.name} – ${item.price}
<button onClick={() => addToCart(item.id)}>Add to Cart</button>
</li>
))}
</ul>
<h2>Cart Total</h2>
<ul>
{cart.map((item) => (
<li key={item.id}>
{item.name} – ${item.price} –
<select
value={item.quantity || 1}
onChange={(e) =>
updateQuantity(item.id, parseInt(e.target.value))
}
>
{[…Array(5).keys()].map((number) => (
<option key={number + 1} value={number + 1}>
{number + 1}
</option>
))}
</select>
<button onClick={() => removeFromCart(item.id)}>Remove</button>
</li>
))}
</ul>
<h2>Total: ${calculateTotal()}</h2>
</div>
);
}

Q) Infinite Scroll Gallery with Lazy Loading

Build an image gallery that loads more images as the user scrolls down the page. Implement lazy loading for improved performance.

import React, { useState, useEffect } from “react”;
import “./styles.css”;

const App = () => {
const [images, setImages] = useState([]);
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(false);

const fetchImages = async () => {
setLoading(true);
try {
// use your client id by register developer account on unplash and create app.
const response = await fetch(
`https://api.unsplash.com/photos/?client_id=weJDI4C21OzgEkJD2ZSkb5yt1aBQwiuHh2tVK4tvS5w&page=${page}`
);
if (!response.ok) {
throw new Error(“Failed to fetch”);
}
const data = await response.json();
if (Array.isArray(data)) {
setImages((prevImages) => […prevImages, …data]);
setPage((prevPage) => prevPage + 1);
} else {
console.error(“Invalid data format:”, data);
}
} catch (error) {
console.error(“Error fetching images:”, error);
} finally {
setLoading(false);
}
};

useEffect(() => {
fetchImages();
}, []);

const handleScroll = () => {
if (
window.innerHeight + document.documentElement.scrollTop !==
document.documentElement.offsetHeight ||
loading
)
return;
fetchImages();
};

useEffect(() => {
window.addEventListener(“scroll”, handleScroll);
return () => window.removeEventListener(“scroll”, handleScroll);
}, [loading]);

return (
<div>
<h1>Image Gallery</h1>
<div className=”image-gallery”>
{images.map((image) => (
<img
key={image.id}
src={image.urls.small}
alt={image.alt_description}
/>
))}
{loading && <p>Loading…</p>}
</div>
</div>
);
};

export default App;

React Interview Questions and Answers 

Q) What is the difference between Virtual DOM and Real DOM?

Virtual DOM Real DOM
Changes can be made easily Changes can be expensive
Minimal memory wastage High demand for memory and more wastage
JSX element is updated if the element exists Creates a new DOM every time an element gets updated
Cannot update HTML directly Able to directly manipulate HTML
Faster updates Slow updates

Q) What is the meaning of JSX?

JSX is the abbreviation for JavaScript XML. It is a file that is used in React to bring out the essence of JavaScript to React and use it for its advantages.

It even includes bringing out HTML and the easy syntax of JavaScript. This ensures that the resulting HTML file will have high readability, thereby relatively increasing the performance of the application.

Consider the following example of a JSX:

render(){
return(
<div>
<h1>Hello Intellipaat learners!</h1>
</div>
);
}
Q) Can browsers read a JSX file?

No, browsers cannot read JSX files directly. It can only read the objects provided by JavaScript. Now, to make a browser read a JSX file, it has to be transformed to a JavaScript object using JSX transformers, and only then it can be fed into the browser for further use in the pipeline.

Q) Why is React widely used today?

React provides users with an ample number of advantages when building an application. Some of them are as follows:

  • With React, UI testing becomes very easy.
  • React can integrate with Angular and other frameworks easily.
  • The high readability index ensures easy understanding.
  • React can be used for both client-side and server-side requirements.
  • It boosts application performance and overall efficiency.

Q) What are events in React?

Whenever there are actions performed in React, such as hovering the mouse or pressing a key on the keyboard, these actions trigger events. Events then perform set activities as a response to these triggers. Handling an event in React is very similar to that in the DOM architecture.

Q) What is/are the debug tool/s for ReactJs?

Some tools to debug the ReactJs codes are:

  1. React DevTools
  2. React Developer Tools in Chrome DevTools
  3. Redux DevTools Extension

Kindly watch the dailyrecruitment.in site for more interview coding questions & answers and Interview questions etc., Here you can download React Coding Questions and Answers easily.

Links for React Coding Questions 1

JOB ALERT ON INSTAGRAM FOLLOW NOW>>
JOB ALERT ON YOUR EMAIL DAILY SUBSCRIBE NOW>>

Govt Jobs by Qualifications

Education & Vacancies Salary Apply Link
10th Pass Govt Jobs - 5,000 Vacancies Rs. 5,200 - 63,200 Apply Now
12th Pass Govt Jobs - 18,000+ Vacancies Rs. 5,200 - 92,300 Apply Now
ITI Pass Jobs - 3,500 Vacancies Rs. 5,200 - 35,000 Apply Now
Any Graduate Jobs - 19,100 Vacancies Rs. 5,200 - 92,300 Apply Now
Central Govt Jobs Rs. 5,200 - 17,000 Apply Now
Bank Jobs - 1,000 Vacancies Rs. 5,200 - 29,200 Apply Now
Diploma Jobs - 9,300 Vacancies Rs. 5,200 - 35,000 Apply Now
BTech/BE Jobs - 18,000 Vacancies Rs. 15,000 - 1,00,000 Apply Now
Data Entry Jobs - 1,300 Vacancies Rs. 5,200 - 29,200 Apply Now
Private Jobs Rs. 10,000 - 67,700 Apply Now