100% found this document useful (1 vote)
24 views15 pages

Comprehensive Interview Question Bank!

The document contains a comprehensive list of interview questions and answers related to React JS, MongoDB, and Node.js, covering topics such as React lifecycle methods, routing, state management, forms, authentication, CRUD operations, querying, integration with Node.js, indexing, basic server creation, file system operations, and middleware. Each section provides detailed explanations and examples to aid understanding. This resource is designed for individuals preparing for technical interviews in these technologies.

Uploaded by

Himalaya singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
24 views15 pages

Comprehensive Interview Question Bank!

The document contains a comprehensive list of interview questions and answers related to React JS, MongoDB, and Node.js, covering topics such as React lifecycle methods, routing, state management, forms, authentication, CRUD operations, querying, integration with Node.js, indexing, basic server creation, file system operations, and middleware. Each section provides detailed explanations and examples to aid understanding. This resource is designed for individuals preparing for technical interviews in these technologies.

Uploaded by

Himalaya singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

React JS Interview Questions (30

Questions)
1. React Lifecycle
Q1: What are React lifecycle methods?​
A: React lifecycle methods are methods that get called at different stages of a component’s
existence, such as when a component is created, updated, or unmounted. Examples include
componentDidMount, componentDidUpdate, and componentWillUnmount.

Q2: What is the difference between componentDidMount and componentWillUnmount?​


A: componentDidMount is invoked immediately after a component is mounted (inserted into
the DOM), often used for data fetching. componentWillUnmount is called right before a
component is unmounted and destroyed, useful for cleanup tasks such as clearing timers or
canceling network requests.

Q3: How do you trigger a re-render in a React component?​


A: A re-render is triggered when the state or props of a component change. You can use
this.setState() in class components or useState() hook in functional components to
update the state and trigger a re-render.

Q4: What is the purpose of shouldComponentUpdate?​


A: shouldComponentUpdate is used to optimize performance by determining whether the
component should re-render or not when state or props change. It returns a boolean value,
true to re-render and false to prevent rendering.

Q5: How do hooks replace lifecycle methods in functional components?​


A: Hooks like useEffect can replace lifecycle methods. For example, useEffect with an
empty dependency array acts like componentDidMount, and cleanup functions inside
useEffect mimic componentWillUnmount.

Q6: What is getDerivedStateFromProps in React?​


A: getDerivedStateFromProps is a static lifecycle method that is invoked right before
rendering. It is used to update the state based on changes in props. It replaces the legacy
componentWillReceiveProps method.
2. Routing in React
Q1: What is React Router?​
A: React Router is a standard library for routing in React. It enables navigation between
different views of a React application and allows the creation of dynamic and nested routes.

Q2: What are the differences between <BrowserRouter> and <HashRouter>?​


A: <BrowserRouter> uses the HTML5 history API to keep the UI in sync with the URL, while
<HashRouter> uses the hash portion of the URL (#) to simulate different pages.

Q3: How can you pass parameters to a route in React Router?​


A: Parameters can be passed to a route using the colon syntax. For example, in the path
/user/:id, id is the parameter. You can access it in the component using the useParams()
hook.

Q4: What is Link in React Router, and how is it different from a regular <a> tag?​
A: The Link component from React Router is used to navigate between routes without
refreshing the page. Unlike the regular <a> tag, which reloads the entire page, Link performs
client-side routing and updates the view without a full page reload.

Q5: How do you implement nested routes in React Router?​


A: Nested routes can be implemented by defining child routes inside a parent route component.
You can use <Route> components nested inside other <Route> components, and in the
component, use useRoutes() to render them.

Q6: What is the Switch component in React Router, and how does it work?​
A: Switch is a component that renders the first child <Route> or <Redirect> that matches
the location. It ensures that only one route is rendered at a time.

3. State Management
Q1: What is the useState hook in React?​
A: The useState hook allows you to add state to functional components in React. It returns an
array with two elements: the current state value and a function to update that state.

Q2: What is the difference between local state and global state?​
A: Local state is specific to a single component and is managed with useState or class
component state, while global state is shared across multiple components, typically managed
with context APIs like React Context or libraries like Redux.
Q3: What is the useReducer hook, and how is it different from useState?​
A: useReducer is a hook used for managing more complex state logic. It is an alternative to
useState and is often used when there are multiple state transitions or complex updates. It
returns the current state and a dispatch function to trigger updates.

Q4: What is Redux and how does it manage state?​


A: Redux is a popular state management library for React. It uses a global store to manage
state, with actions dispatched to reducers that modify the state based on the action type.

Q5: What are actions in Redux?​


A: Actions in Redux are plain JavaScript objects that describe the type of event that occurred.
They must have a type field that describes the action, and optionally other fields with data.

Q6: How is Context API different from Redux?​


A: The Context API is a built-in React feature for passing state between components without
props drilling, while Redux is a more robust state management solution with a central store and
predictable reducers.

4. Forms in React
Q1: How do you handle form inputs in React?​
A: Form inputs in React are controlled using the useState hook for functional components or
state in class components. The value of the input is bound to the state, and the onChange
event is used to update the state as the user types.

Q2: What is the difference between controlled and uncontrolled components in React
forms?​
A: Controlled components are those where form data is handled by the React component state,
whereas uncontrolled components use refs to directly access the DOM elements to get form
values.

Q3: How do you handle form validation in React?​


A: Form validation in React can be handled by manually checking the input values in the
onSubmit handler or using libraries like Formik or React Hook Form for more complex
validation rules.

Q4: How can you submit a form in React?​


A: A form in React can be submitted by handling the onSubmit event. You can prevent the
default browser behavior with event.preventDefault() and manually process the form
data.
Q5: What is React Hook Form and how does it help with form handling?​
A: React Hook Form is a library that makes handling forms in React more efficient. It
reduces the need for boilerplate code and provides easy validation, managing form state with
less re-renders.

Q6: How can you reset a form in React?​


A: You can reset a form by clearing the state associated with the form fields, either by manually
setting each field to its initial value or using libraries like React Hook Form that provide reset
functionality.

5. React Authentication
Q1: How do you handle authentication in React?​
A: Authentication in React can be handled by using token-based systems like JWT (JSON Web
Tokens). After logging in, the user receives a token, which is stored (usually in localStorage or
sessionStorage) and is included in subsequent requests to protected routes.

Q2: What is a higher-order component (HOC) and how is it used for authentication?​
A: A higher-order component (HOC) is a function that takes a component and returns a new
component. It can be used for authentication by wrapping protected components, checking if the
user is authenticated before rendering the component.

Q3: How can you secure routes in React?​


A: Routes in React can be secured by using route guards. This is typically done by checking if
a user is authenticated before allowing access to certain routes. If the user is not authenticated,
they can be redirected to a login page.

Q4: What is the role of localStorage in React authentication?​


A: localStorage is used to store authentication tokens (e.g., JWT) so that the user's session
can persist across page reloads. However, it’s important to handle tokens securely to prevent
vulnerabilities.

Q5: How do you implement social login (e.g., Google, Facebook) in React?​
A: Social login can be implemented in React using OAuth providers like Google or Facebook.
You can use libraries like react-oauth/google or implement OAuth flows manually by
interacting with the provider’s API.

Q6: What are the security risks to consider in React authentication?​


A: Common security risks include storing tokens insecurely (e.g., in localStorage), cross-site
scripting (XSS), and CSRF attacks. It’s important to sanitize inputs, use HTTPS, and employ
security best practices when implementing authentication.
MongoDB Interview Questions (20
Questions)
1. CRUD Operations
Q1: What does CRUD stand for in MongoDB?​
A: CRUD stands for Create, Read, Update, and Delete, which are the basic operations for
managing data in a MongoDB database.

Q2: How do you insert a single document into a MongoDB collection?​


A: You can insert a document using the insertOne() method.

Example: db.collection.insertOne({ name: "Alice", age: 25 });

Q3: How do you read documents from a MongoDB collection?​


A: You can read documents using the find() method. Example:

db.collection.find({ age: { $gte: 18 } });

Q4: How can you update a document in MongoDB?​


A: You can update a document using updateOne() or updateMany() with update operators
like $set.

Example db.collection.updateOne({ name: "Alice" }, { $set: { age: 26 } });

Q5: How do you delete a document from a MongoDB collection?​


A: You can delete a document using deleteOne() or deleteMany().

Example: db.collection.deleteOne({ name: "Alice" });

2. Querying
Q1: What is a query in MongoDB, and how do you perform a basic query?​
A: A query in MongoDB retrieves data from a collection. You can perform a basic query using
the find() method.

Example: db.collection.find({ name: "Alice" });


Q2: How do you perform a query with a comparison operator in MongoDB?​
A: MongoDB supports comparison operators like $eq, $ne, $gt, $lt, etc.

Example: db.collection.find({ age: { $gt: 20 } });

Q3: How do you query for documents with a logical operator in MongoDB?​
A: MongoDB allows logical operators like $and, $or, $not.

Example: db.collection.find({ $or: [{ age: { $lt: 18 } }, { age: { $gt: 60 } }] });

Q4: How can you project specific fields in MongoDB queries?​


A: You can project specific fields using the second argument of the find() method.

Example: db.collection.find({ name: "Alice" }, { name: 1, age: 1, _id: 0 });

Q5: How do you perform text search queries in MongoDB?​


A: MongoDB supports text search with the $text operator on fields indexed for text.

Example: db.collection.find({ $text: { $search: "developer" } });

3. Integration with Node.js


Q1: How do you connect a Node.js application to MongoDB?​
A: You can connect a Node.js app to MongoDB using the mongodb or mongoose package.
Example using mongodb package:

const { MongoClient } = require('mongodb');


const client = new MongoClient('mongodb://localhost:27017');
await client.connect();

Q2: What is Mongoose, and why is it used in Node.js?​


A: Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides
schema-based models and simplifies interactions with MongoDB.
Q3: How can you create a schema and model in Mongoose?​
A: You can create a schema and model using the mongoose.Schema() and
mongoose.model() functions.

Example:

const userSchema = new mongoose.Schema({ name: String, age: Number });


const User = mongoose.model('User', userSchema);

Q4: How do you perform CRUD operations using Mongoose in Node.js?​


A: You can use Mongoose model methods such as create(), find(), updateOne(), and
deleteOne() for CRUD operations.

Example: User.find({ name: 'Alice' });

Q5: How do you handle errors in MongoDB operations using Node.js?​


A: Errors in MongoDB operations can be handled using try-catch blocks or .catch() for
promises. Example:

try {
await User.find();
} catch (error) {
console.error(error);
}

4. Indexing in MongoDB
Q1: What is indexing in MongoDB, and why is it important?​
A: Indexing in MongoDB helps to improve the performance of search queries by reducing the
number of documents MongoDB scans. It is essential for optimizing read operations.

Q2: How do you create an index in MongoDB?​


A: You can create an index using the createIndex() method.

Example: db.collection.createIndex({ name: 1 });

Q3: What are compound indexes in MongoDB?​


A: Compound indexes are indexes that include multiple fields. They help optimize queries that
filter by more than one field.

Example: db.collection.createIndex({ name: 1, age: -1 });


Q4: How do you view existing indexes in a MongoDB collection?​
A: You can view all indexes in a collection using the getIndexes() method.

Example: db.collection.getIndexes();

Q5: What is the TTL (Time-To-Live) index in MongoDB?​


A: A TTL index is used to automatically remove documents from a collection after a certain
period. It is useful for managing expiring data such as sessions or logs.

Example: db.collection.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 });

Node.js Interview Questions (20


Questions)
1. Basic Server
Q1: How do you create a basic HTTP server in Node.js?​
A: You can create a basic HTTP server using the built-in http module. Example:

const http = require('http');


const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!');
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});

Q2: What is the role of the require() function in Node.js?​


A: The require() function is used to import modules, JSON, and local files into a Node.js
application.
Q3: How do you stop a running Node.js server?​
A: You can stop a running Node.js server by pressing Ctrl + C in the terminal where the
server is running.

Q4: What is the res.writeHead() method in Node.js?​


A: The res.writeHead() method is used to send a status code and HTTP headers in the
response.

Example: res.writeHead(200, { 'Content-Type': 'text/html' });

Q5: How do you install external packages in a Node.js project?​


A: You can install external packages using npm (Node Package Manager).

Example: npm install express

2. File System
Q1: How do you read a file asynchronously in Node.js?​
A: You can use the fs.readFile() method to read a file asynchronously. Example:

const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});

Q2: How do you write to a file in Node.js?​


A: You can use the fs.writeFile() method to write to a file. Example:

fs.writeFile('file.txt', 'Hello World', (err) => {


if (err) throw err;
console.log('File written successfully');
});

Q3: How do you delete a file in Node.js?​


A: You can use the fs.unlink() method to delete a file. Example:

fs.unlink('file.txt', (err) => {


if (err) throw err;
console.log('File deleted');
});
Q4: How do you check if a file exists in Node.js?​
A: You can use the fs.existsSync() method to check if a file exists. Example:

if (fs.existsSync('file.txt')) {
console.log('File exists');
}

Q5: How do you append data to a file in Node.js?​


A: You can use the fs.appendFile() method to append data to a file. Example:

fs.appendFile('file.txt', 'New data', (err) => {


if (err) throw err;
console.log('Data appended');
});

3. Middleware
Q1: What is middleware in Node.js?​
A: Middleware functions in Node.js are functions that have access to the request object (req),
response object (res), and the next middleware function in the application’s request-response
cycle.

Q2: How do you use middleware in Express.js?​


A: In Express.js, middleware is used by calling the use() method. Example:

const express = require('express');


const app = express();

app.use((req, res, next) => {


console.log('Middleware function executed');
next();
});

Q3: What are third-party middleware in Express.js?​


A: Third-party middleware are middleware modules that can be installed via npm and
integrated into Express.js applications, such as morgan, body-parser, etc.
Q4: How do you handle errors with middleware in Express.js?​
A: Error-handling middleware functions in Express.js have four arguments: err, req, res, and
next. Example:

app.use((err, req, res, next) => {


console.error(err.stack);
res.status(500).send('Something went wrong!');
});

Q5: How do you add middleware to handle JSON requests in Express.js?​


A: You can use the express.json() middleware to handle JSON requests.

Example: app.use(express.json());

4. Single-threaded Application
Q1: Is Node.js single-threaded, and how does it handle concurrency?​
A: Yes, Node.js is single-threaded, but it uses non-blocking I/O and an event-driven
architecture to handle multiple requests concurrently via an event loop.

Q2: What is the event loop in Node.js?​


A: The event loop is a mechanism in Node.js that allows it to perform non-blocking I/O
operations by offloading tasks to the system kernel when possible.

Q3: How does Node.js manage blocking operations in a single-threaded environment?​


A: Node.js handles blocking operations by offloading them to background threads or the
system's underlying API, allowing other operations to continue in the event loop.

Q4: What are worker threads in Node.js?​


A: Worker threads allow Node.js to run JavaScript code in parallel on multiple threads. It is
useful for CPU-intensive tasks but is not often used for I/O operations.

Q5: Can Node.js run on multiple cores of a CPU?​


A: Node.js is single-threaded by default, but it can run on multiple cores using the cluster
module or worker threads to spawn multiple processes.
Express.js Interview Questions (20
Questions)
1. Request and Response
Q1: How do you handle a GET request in Express.js?​
A: You handle a GET request by defining a route using the app.get() method. Example:

app.get('/users', (req, res) => {


res.send('User list');
});

Q2: How do you access query parameters in an Express.js request?​


A: Query parameters can be accessed using req.query. Example:

app.get('/search', (req, res) => {


const searchTerm = req.query.q;
res.send(`You searched for: ${searchTerm}`);
});

Q3: How do you send a JSON response in Express.js?​


A: You can send a JSON response using the res.json() method. Example:

app.get('/data', (req, res) => {


res.json({ name: 'John', age: 30 });
});

Q4: How do you send a status code along with a response in Express.js?​
A: You can send a status code using the res.status() method. Example:

app.get('/notfound', (req, res) => {


res.status(404).send('Page not found');
});

Q5: How do you handle POST requests and access request body data in Express.js?​
A: To handle POST requests and access body data, use app.post() and middleware like
express.json() or express.urlencoded(). Example:
app.use(express.json());
app.post('/submit', (req, res) => {
const data = req.body;
res.send(`Received: ${JSON.stringify(data)}`);
});

2. Error Handling
Q1: How do you handle errors in Express.js?​
A: In Express.js, errors can be handled using a middleware function with four arguments: err,
req, res, and next. Example:

app.use((err, req, res, next) => {


console.error(err.stack);
res.status(500).send('Something went wrong!');
});

Q2: How do you create custom error messages in Express.js?​


A: You can create custom error messages by throwing an error inside a route handler.
Example:

app.get('/error', (req, res, next) => {


const err = new Error('Custom error message');
err.status = 400;
next(err);
});

Q3: How do you pass errors to the next middleware in Express.js?​


A: You can pass errors to the next middleware by using the next() function with an error
argument. Example:

app.get('/error', (req, res, next) => {


next(new Error('An error occurred'));
});

Q4: How do you handle 404 errors in Express.js?​


A: To handle 404 errors, you can add a middleware function at the end of your route definitions
to catch unmatched routes. Example:

app.use((req, res) => {


res.status(404).send('Page not found'); });
Q5: How do you differentiate between operational errors and programming errors in
Express.js?​
A: Operational errors are runtime issues like invalid input or network failures, which are
expected and should be handled gracefully. Programming errors are bugs in the application
code and often crash the process, requiring different handling.

3. Connecting with MongoDB


Q1: How do you connect an Express.js app to MongoDB?​
A: You can connect to MongoDB using the mongoose package. Example:

const mongoose = require('mongoose');


mongoose.connect('mongodb://localhost:27017/mydb', { useNewUrlParser: true,
useUnifiedTopology: true });

Q2: How do you define a schema and model in Mongoose?​


A: You define a schema using mongoose.Schema and a model using mongoose.model().
Example:

const userSchema = new mongoose.Schema({


name: String,
age: Number,
});
const User = mongoose.model('User', userSchema);

Q3: How do you insert a document into a MongoDB collection in Express.js?​


A: You can insert a document using the save() method in Mongoose. Example:

const user = new User({ name: 'John', age: 30 });


user.save().then(() => console.log('User saved'));

Q4: How do you query a MongoDB collection in Express.js?​


A: You can query a MongoDB collection using methods like find(), findOne(), or
findById(). Example:

User.find({ age: 30 }).then((users) => console.log(users));


Q5: How do you update a document in MongoDB from an Express.js app?​
A: You can update a document using updateOne() or findByIdAndUpdate() in
Mongoose. Example:

User.updateOne({ name: 'John' }, { age: 31 }).then(() => console.log('User updated'));

4. Scaffolding
Q1: What is scaffolding in Express.js?​
A: Scaffolding in Express.js refers to the process of generating the basic structure of an
Express app, often using a tool like express-generator.

Q2: How do you create a new Express.js project using express-generator?​


A: You can create a new Express.js project by installing the express-generator globally
and running the command:

npx express-generator myapp

Q3: What is the directory structure of an Express.js app generated by


express-generator?​
A: The directory structure includes folders like bin/, public/, routes/, views/, and files
like app.js, package.json.

Q4: How do you run an Express.js app created with express-generator?​


A: After creating the app, navigate to the project folder, install dependencies with npm
install, and run the app using:

npm start

Q5: What are the benefits of using scaffolding tools like express-generator?​
A: Scaffolding tools like express-generator provide a standard folder structure, boilerplate
code, and essential configurations, which help speed up the development process and ensure a
clean organization of the project.

You might also like