4.1 Answers - Top 200 Mern Interview Questions
4.1 Answers - Top 200 Mern Interview Questions
It ensures
MERN Stack Interview Questions data durability and allows for failover in
case of server failure.
○ Example: MongoDB uses replica sets,
MongoDB
which are groups of MongoDB servers with
one primary and multiple secondary nodes.
1. What is MongoDB? How is it different from SQL
6. What is indexing in MongoDB?
databases?
○ Indexing in MongoDB improves the
○ MongoDB is a NoSQL database that stores
performance of search operations by
data in flexible, JSON-like documents.
creating data structures that store a small
Unlike SQL databases which use tables
portion of the data set.
and rows to store data, MongoDB uses
collections and documents.
Example:
javascript
Example:
Copy code
json
db.collection.createIndex({ name: 1 });
Copy code
{
○
"_id": "123",
7. How does sharding work in MongoDB?
"name": "John Doe", ○ Sharding is a method for distributing data
"age": 30, across multiple machines. MongoDB uses
"address": { sharding to support deployments with large
"street": "123 Main St", data sets and high throughput operations.
"city": "New York" ○ Example: MongoDB uses a shard key to
distribute data across shards, ensuring
}
even data distribution.
}
8. Discuss the types of NoSQL databases.
○ Types include Document-based (e.g.,
○ MongoDB), Key-Value (e.g., Redis),
2. Explain the structure of a MongoDB document. Column-family (e.g., Cassandra), and
○ A MongoDB document is a JSON-like Graph databases (e.g., Neo4j).
structure with field-value pairs. Each ○ Example: Redis stores data as key-value
document has a unique identifier _id. pairs, while MongoDB stores data as
JSON-like documents.
Example: 9. What is GridFS in MongoDB?
json ○ GridFS is a specification for storing and
Copy code retrieving large files in MongoDB. It splits
{ files into smaller chunks and stores each
"_id": "123", chunk as a separate document.
"name": "Alice",
Example:
"email": "alice@example.com",
javascript
"tags": ["developer", "blogger"]
Copy code
} const bucket = new GridFSBucket(db, {
bucketName: 'files' });
○
3. What is BSON? Why is it used in MongoDB?
○
○ BSON (Binary JSON) is a binary
10. How does MongoDB ensure high availability?
representation of JSON-like documents. It
○ MongoDB ensures high availability through
extends the JSON model to provide
replica sets and automatic failover. If the
additional data types and to be efficient in
primary node fails, a secondary node is
encoding and decoding within MongoDB.
automatically promoted to primary.
○ Example: BSON supports additional data
○ Example: MongoDB's replica set
types like Date and Binary that JSON does
architecture provides redundancy and
not.
failover capabilities.
4. Differentiate between MongoDB and MySQL.
○ MongoDB is schema-less, uses collections
and documents, and supports horizontal Express.js
scaling. MySQL is schema-based, uses
tables and rows, and traditionally supports 11. What is Express.js?
vertical scaling. ○ Express.js is a fast, unopinionated,
○ Example: In MongoDB, you can have a minimalist web framework for Node.js used
collection with documents having different to build web applications and APIs.
fields, while in MySQL, all rows in a table
must have the same columns. Example:
5. Explain MongoDB's replication and its javascript
importance. Copy code
○ Replication in MongoDB involves const express = require('express');
distributing data across multiple servers for
const app = express(); ○
17. Explain the role of body-parser middleware.
○ ○ body-parser middleware is used to parse
12. Explain middleware in Express.js with an the incoming request bodies before your
example. handlers, available under req.body.
○ Middleware functions are functions that
execute during the lifecycle of a request to Example:
the server. They have access to the request javascript
and response objects. Copy code
const bodyParser = require('body-parser');
Example: app.use(bodyParser.json());
javascript
Copy code
○
app.use((req, res, next) => { 18. How can you set up a RESTful API using
console.log('Middleware executed'); Express.js?
next(); ○ Setting up a RESTful API involves defining
}); routes for different CRUD operations.
○ Example:
13. How does routing work in Express.js? javascript
○ Routing refers to defining application Copy code
endpoints and how they respond to client app.get('/api/users', (req, res) =>
requests. res.send('Get all users'));
app.post('/api/users', (req, res) =>
Example: res.send('Create user'));
javascript
app.put('/api/users/:id', (req, res) =>
Copy code
res.send('Update user'));
app.get('/user/:id', (req, res) => {
app.delete('/api/users/:id', (req, res) =>
res.send(`User ID: ${req.params.id}`);
res.send('Delete user'));
});
○
○
19. Discuss the significance of next() function in
14. What are the advantages of using Express.js?
middleware.
○ Advantages include ease of use, robust
○ The next() function is used to pass
routing, middleware support, and integration
control to the next middleware function in
with many templating engines.
the stack.
○ Example: Express.js makes it easy to set
up a server and handle different HTTP
requests. Example:
15. Differentiate between app.use() and app.get() javascript
methods. Copy code
○ app.use() is used to apply middleware, app.use((req, res, next) => {
whereas app.get() is used to define a console.log('First middleware');
route handler for GET requests. next();
});
Example:
javascript ○
Copy code 20. What is the difference between res.send() and
app.use(express.json()); // Middleware res.json()?
app.get('/users', (req, res) => res.send('Users ○ res.send() can send various types of
endpoint')); // Route handler responses (e.g., string, buffer), while
res.json() sends a JSON response.
○
16. How does error handling work in Express.js? Example:
○ Error handling in Express.js is done using javascript
middleware functions that have four Copy code
arguments: err, req, res, next. res.send('Hello World'); // Sends a string
response
Example: res.json({ message: 'Hello World' }); // Sends
javascript a JSON response
Copy code
app.use((err, req, res, next) => { ○
console.error(err.stack);
res.status(500).send('Something broke!'); React
});
21. What is React and why is it used? 25. Explain the lifecycle methods of React
○ React is a JavaScript library for building components.
user interfaces, particularly single-page ○ Lifecycle methods are hooks that allow
applications. It allows developers to create developers to run code at particular times in
large web applications that can update and a component's lifecycle.
render efficiently.
Example:
Example: javascript
javascript Copy code
Copy code class MyComponent extends React.Component {
const element = <h1>Hello, world!</h1>; componentDidMount() {
ReactDOM.render(element, // Runs after the component output has been
document.getElementById('root')); rendered to the DOM
}
○ componentDidUpdate(prevProps, prevState) {
22. Explain the virtual DOM in React.
// Runs after the component updates
○ The virtual DOM is an in-memory
}
representation of the real DOM elements
generated by React components. React componentWillUnmount() {
updates the virtual DOM first, then // Runs before the component is removed
efficiently updates the real DOM. from the DOM
○ Example: React uses a diffing algorithm to }
minimize the number of changes applied to }
the actual DOM.
23. What are state and props in React?
○
○ State is a built-in React object used to hold
26. What are keys in React and why are they
data or information about the component.
important?
Props are inputs to components that allow
○ Keys help React identify which items have
data to be passed from one component to
changed, are added, or are removed. They
another.
should be given to elements inside an array
to give them a stable identity.
Example:
javascript
Example:
Copy code
javascript
class MyComponent extends React.Component {
Copy code
constructor(props) { const listItems = items.map(item => <li
super(props); key={item.id}>{item.name}</li>);
this.state = { count: 0 };
} ○
render() { 27. How does React Router work?
return <div>{this.props.message} - ○ React Router is a library for routing in React
{this.state.count}</div>; applications. It enables navigation between
} views of various components in a React
application.
}
Example:
○
javascript
24. Differentiate between controlled and uncontrolled
Copy code
components in React.
import { BrowserRouter as Router, Route, Switch
○ Controlled components have their state
controlled by React, whereas uncontrolled } from 'react-router-dom';
components maintain their own state <Router>
internally. <Switch>
<Route path="/home" component={Home} />
Example: <Route path="/about" component={About} />
javascript </Switch>
Copy code
</Router>
// Controlled
<input type="text" value={this.state.value} ○
onChange={this.handleChange} /> 28. What are Higher Order Components (HOCs) in
// Uncontrolled React?
<input type="text" defaultValue="default value" ○ HOCs are functions that take a component
ref={this.inputRef} /> and return a new component with added
functionality.
○
Example:
javascript
Copy code determined by events such as user actions,
function withLoading(Component) { sensor outputs, or messages from other
return function EnhancedComponent(props) { programs/threads.
return props.isLoading ? <LoadingSpinner />
: <Component {...props} />; Example: Using EventEmitter in Node.js.
javascript
}
Copy code
}
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
○
29. Explain the significance of setState() method. myEmitter.on('event', () => {
○ setState() is used to update the state console.log('An event occurred!');
object and re-render the component. });
myEmitter.emit('event');
Example:
javascript ○
Copy code 33. How does Node.js handle child threads?
this.setState({ count: this.state.count + 1 }); ○ Node.js uses single-threaded event loops
for handling asynchronous operations but
○ can create child processes using the
30. What are hooks in React and how do you use child_process module.
them?
○ Hooks are functions that let you use state Example:
and other React features without writing a javascript
class. Copy code
const { exec } = require('child_process');
Example: exec('ls', (error, stdout, stderr) => {
javascript if (error) {
Copy code
console.error(`exec error: ${error}`);
import { useState } from 'react';
return;
function Example() {
}
const [count, setCount] = useState(0);
console.log(`stdout: ${stdout}`);
return <button onClick={() => setCount(count
console.error(`stderr: ${stderr}`);
+ 1)}>{count}</button>;
});
}
○
○ 34. What is npm and what is its role in Node.js?
○ npm (Node Package Manager) is a
Node.js package manager for JavaScript, and it is
the default package manager for Node.js. It
31. What is Node.js? helps in installing, sharing, and managing
○ Node.js is a runtime environment that dependencies in a Node.js project.
allows JavaScript to be run on the server
side. It is built on Chrome's V8 JavaScript Example: Installing Express.js.
engine. bash
Copy code
Example: Running a simple server with Node.js. npm install express
javascript
Copy code ○
const http = require('http'); 35. How does Node.js support asynchronous
const server = http.createServer((req, res) => operations?
{ ○ Node.js supports asynchronous operations
res.statusCode = 200; using callbacks, promises, and async/await
res.setHeader('Content-Type', 'text/plain'); syntax.
res.end('Hello World\n');
Example: Using Promises in Node.js.
});
javascript
server.listen(3000, () => { Copy code
console.log('Server running at const fs = require('fs').promises;
http://localhost:3000/'); async function readFile() {
}); try {
const data = await
○ fs.readFile('/path/to/file', 'utf8');
32. Explain the event-driven programming in Node.js.
console.log(data);
○ Event-driven programming in Node.js
means that the flow of the program is } catch (err) {
console.error(err); Copy code
} const fs = require('fs');
} const readStream =
readFile(); fs.createReadStream('example.txt', 'utf8');
readStream.on('data', chunk => {
○ console.log(chunk);
36. Discuss the use cases of Node.js. });
○ Node.js is used for building scalable
network applications, real-time web ○
applications, microservices architecture, 40. How does error handling work in Node.js?
REST APIs, and command-line tools. ○ Error handling in Node.js is done using
○ Example: Real-time chat application using try-catch blocks, event emitters, and
Node.js and WebSockets. callback functions.
37. Explain the purpose of package.json file in
Node.js projects.
Example: Handling errors in a callback.
○ The package.json file holds metadata javascript
relevant to the project and lists Copy code
dependencies and scripts for the project. fs.readFile('/path/to/file', (err, data) => {
if (err) {
Example:
console.error('Error reading file:', err);
json
Copy code return;
{ }
"name": "my-project", console.log(data);
"version": "1.0.0", });
"main": "index.js",
"dependencies": { ○
"express": "^4.17.1"
}, Full-Stack Development
"scripts": {
General Concepts
"start": "node index.js"
}
41. What is full-stack development?
} ○ Full-stack development refers to the
development of both the front-end
○ (client-side) and back-end (server-side)
38. How can you create a simple web server using portions of a web application.
Node.js? ○ Example: A full-stack developer might use
○ Using the http module to create a simple React for the front end and Node.js with
web server. MongoDB for the back end.
42. Explain the MVC (Model-View-Controller)
Example: architecture.
javascript ○ MVC is a design pattern that separates an
Copy code application into three main logical
const http = require('http'); components: Model, View, and Controller.
const server = http.createServer((req, res) => ○ Example:
■ Model: Represents the data layer
{
(e.g., MongoDB models).
res.statusCode = 200; ■ View: Represents the UI layer
res.setHeader('Content-Type', 'text/plain'); (e.g., React components).
res.end('Hello World\n'); ■ Controller: Handles the business
}); logic (e.g., Express.js route
server.listen(3000, () => { handlers).
43. What are microservices and why are they used in
console.log('Server running at
full-stack development?
http://localhost:3000/');
○ Microservices are an architectural style that
}); structures an application as a collection of
loosely coupled services. They are used for
○ better scalability and maintainability.
39. What are streams in Node.js? ○ Example: Breaking down a monolithic
○ Streams are objects that enable reading application into smaller, independently
data or writing data in a continuous fashion. deployable services.
There are four types of streams: readable, 44. Discuss the advantages and disadvantages of
writable, duplex, and transform. microservices architecture.
○ Advantages: Scalability, flexibility, isolated
Example: Reading a file stream. failures, technology diversity.
javascript
○ Disadvantages: Complexity in ■ Implement proper authentication
management, inter-service communication, and authorization.
data consistency challenges. ■ Use secure cookies.
○ Example: Microservices can be scaled ■ Regularly update dependencies.
independently based on demand.
45. What is RESTful API and how does it work? Frontend Development
○ A RESTful API is an API that conforms to
REST architectural constraints. It uses 51. What are the differences between inline, block,
standard HTTP methods and status codes and inline-block elements?
for operations. ○ Inline: Does not start on a new line, only
takes as much width as necessary (e.g.,
Example: <span>).
javascript ○ Block: Starts on a new line, takes up full
Copy code width (e.g., <div>).
app.get('/api/users', (req, res) => ○ Inline-block: Does not start on a new line
res.send('Get all users')); but respects width and height (e.g., <img>).
52. Explain responsive design and its importance in
○ web development.
46. What are the differences between SOAP and ○ Responsive design ensures web pages
REST? render well on a variety of devices and
○ SOAP: Protocol, XML-based, strict window or screen sizes.
standards.
○ REST: Architectural style, uses multiple Example: Using media queries in CSS.
formats (JSON, XML), more flexible. css
○ Example: REST APIs are typically easier to Copy code
use and more scalable than SOAP APIs. @media (max-width: 600px) {
47. Explain the concept of CORS (Cross-Origin
.container {
Resource Sharing).
○ CORS is a security feature that allows or width: 100%;
restricts resources on a web page to be }
requested from another domain outside the }
domain from which the resource originated.
○
Example: Enabling CORS in Express.js. 53. What are CSS preprocessors and what are their
javascript benefits?
Copy code ○ CSS preprocessors like SASS or LESS
const cors = require('cors'); extend CSS with variables, nested rules,
app.use(cors()); and functions.
ChatGPT
app.post('/upload', upload.single('file'),
(req, res) => {
70. What are the different types of HTTP status codes
and their meanings? // Process uploaded file
○ 1xx Informational: Request received, res.send('File uploaded successfully.');
continuing process. });
○ 2xx Success: The action was successfully
received, understood, and accepted. ○
○ 3xx Redirection: Further action needs to 74. What is GraphQL and how does it differ from
be taken in order to complete the request. REST?
○ 4xx Client Error: The request contains bad ○ GraphQL is a query language for APIs and
syntax or cannot be fulfilled. a runtime for executing those queries. It
allows clients to request exactly the data ○
they need, making it more efficient than 80. What are the common security threats to web
REST APIs for certain types of applications. applications and how can you mitigate them?
○ Examples:
Example: ■ Cross-Site Scripting (XSS):
graphql Sanitize user inputs, encode
Copy code output.
query { ■ SQL Injection: Use prepared
user(id: 1) { statements or ORM.
■ Cross-Site Request Forgery
name
(CSRF): Use tokens and check
email referer headers.
} ■ Clickjacking: Use
} frame-ancestors and
X-Frame-Options headers.
○
75. Explain the purpose of WebSockets and how they These questions cover a wide range of topics in full-stack
differ from HTTP. development, including frontend, backend, and general
○ WebSockets provide a full-duplex concepts like security and architecture. Each question provides
communication channel over a single TCP an opportunity to discuss fundamental concepts, best practices,
connection, enabling real-time data transfer and real-world examples. If you have more specific questions or
between clients and servers. HTTP, on the need further clarification on any topic, feel free to ask!
other hand, is stateless and typically follows
a request-response model. 3.5
○ Example: Real-time chat application using
WebSockets for instant messaging. continue
76. Discuss the advantages and disadvantages of
using microservices architecture.
ChatGPT
○ Advantages: Scalability, flexibility, isolated
failures, technology diversity.
Certainly! Let's continue with more questions and examples
○ Disadvantages: Complexity in
related to MERN stack, full-stack development, and related
management, inter-service communication,
technologies:
data consistency challenges.
○ Example: Using Docker for containerization
to simplify deployment and management of 81. What is continuous integration (CI) and
microservices. continuous deployment (CD)?
77. What are serverless architectures and how do ○ Continuous Integration (CI): The practice
they work? of frequently merging code changes into a
○ Serverless architectures allow developers shared repository, where automated tests
to build and run applications without and builds are run.
managing servers. The cloud provider ○ Continuous Deployment (CD): Extends CI
automatically provisions, scales, and by automatically deploying code changes to
manages the infrastructure required to run production environments after passing
the code. tests.
○ Example: Using AWS Lambda functions to ○ Example: Using Jenkins or GitLab CI/CD
execute code without provisioning or pipelines to automate testing and
managing servers. deployment.
78. How can you secure a RESTful API? 82. How can you automate the deployment of a web
○ Examples: application?
■ Use HTTPS. ○ Automate deployment using tools like
■ Implement authentication and Jenkins, GitLab CI/CD, or Docker with
authorization (JWT, OAuth). Kubernetes for container orchestration.
■ Validate and sanitize inputs. ○ Example: Using a Dockerfile and
■ Rate limiting and IP whitelisting. docker-compose.yml to define the
79. Explain the concept of middleware in Express.js. application environment and deployment
○ Middleware functions are functions that process.
have access to the request object (req), the 83. Explain the role of Docker in containerization.
response object (res), and the next ○ Docker provides a platform for developers
middleware function in the application's to build, ship, and run applications in
request-response cycle. containers, enabling consistency across
different environments.
○ Example: Dockerizing a Node.js application
Example: Logging middleware in Express.js.
to package dependencies and
javascript
configurations into a lightweight container.
Copy code
84. What are the advantages of using containerization
app.use((req, res, next) => {
in deployment?
console.log('Time:', Date.now()); ○ Advantages: Isolation, consistency,
next(); scalability, portability, resource efficiency.
});
○ Example: Deploying microservices in requests, database events, or scheduled
separate Docker containers to manage events without provisioning or managing
dependencies and scale independently. servers.
85. How does load balancing work and why is it 92. Explain GraphQL and how it differs from REST.
important? ○ GraphQL is a query language for APIs that
○ Load balancing distributes incoming allows clients to request specific data and
network traffic across multiple servers to aggregate multiple resources in a single
ensure optimal resource utilization, request, providing more flexibility and
reliability, and performance. efficiency compared to traditional REST
○ Example: Using Nginx or HAProxy to APIs.
distribute HTTP requests across backend ○ Example: Querying nested data in a single
servers based on predefined algorithms. GraphQL request to fetch user information
86. Discuss the differences between horizontal and and related posts.
vertical scaling. 93. What are progressive web apps (PWAs) and their
○ Horizontal Scaling: Adding more machines advantages?
or nodes to a system to distribute load ○ PWAs are web applications that leverage
across multiple instances. modern web capabilities to provide a native
○ Vertical Scaling: Increasing the capacity of app-like experience, including offline
existing machines or nodes (e.g., adding support, push notifications, and fast loading
more CPU, RAM) to handle increased load. times.
○ Example: Horizontal scaling using AWS ○ Example: Building a PWA with service
Auto Scaling to automatically add or workers to cache resources for offline
remove EC2 instances based on traffic. access and improve performance.
87. What are the key considerations for deploying a 94. Discuss the concept of micro frontends.
web application to the cloud? ○ Micro frontends is an architectural style
○ Considerations include scalability, where frontend applications are composed
availability, security, cost management, data of independently deployable, smaller
management, and compliance frontend components owned by different
requirements. teams, promoting isolation, scalability, and
○ Example: Deploying a Node.js application maintainability.
to AWS Elastic Beanstalk with auto-scaling ○ Example: Using web components or
and load balancing configurations. iframes to integrate micro frontends into a
88. How can you monitor the performance of a unified user interface.
deployed web application? 95. How does AI and machine learning integrate with
○ Use monitoring tools like Prometheus, full-stack development?
Grafana, AWS CloudWatch, or New Relic to ○ AI and machine learning can be integrated
track metrics such as response time, error into full-stack development to enhance user
rates, and resource utilization. experience, automate tasks, improve
○ Example: Setting up Grafana dashboards to decision-making, and analyze large
visualize application metrics and datasets for insights.
performance trends. ○ Example: Using TensorFlow.js to integrate
89. Explain blue-green deployment and its benefits. machine learning models into a React
○ Blue-green deployment is a technique that application for real-time image recognition.
reduces downtime and risk by running two 96. What are WebAssembly and its use cases in web
identical production environments, with only development?
one live environment at a time. ○ WebAssembly (Wasm) is a binary
○ Example: Deploying a new version (green) instruction format that enables
alongside the current version (blue), then high-performance execution of code on web
switching traffic to green after successful browsers, allowing developers to run
testing. languages other than JavaScript (e.g., C++,
90. What are the common security practices for Rust) in web applications.
deploying web applications? ○ Example: Compiling C++ code to
○ Practices include using HTTPS, securing WebAssembly for efficient client-side
APIs with authentication and authorization computations in a web application.
mechanisms (JWT, OAuth), regular security 97. Explain the principles of test-driven development
audits, and vulnerability assessments. (TDD).
○ Example: Implementing OWASP Top 10 ○ TDD is a software development approach
security controls to protect against common where tests are written before the actual
web application security risks. code implementation, guiding the
91. What is serverless architecture and how does it development process to ensure code
work? quality, maintainability, and functionality.
○ Serverless architecture allows developers ○ Example: Writing unit tests using Jest or
to build and run applications without Mocha before implementing a new feature
managing servers. Applications are broken or fixing a bug in a React component.
into individual functions that run in a 98. What are the differences between unit testing and
stateless compute containers triggered by integration testing?
events. ○ Unit Testing: Tests individual components
○ Example: Using AWS Lambda to execute or modules in isolation to verify their
backend logic in response to HTTP correctness.
○ Integration Testing: Tests interactions console.log(factorial(5)); // Output: 120 (5! =
between integrated components or modules 5 * 4 * 3 * 2 * 1 = 120)
to ensure they work together as expected. ```
○ Example: Testing a React component (unit
testing) versus testing API endpoints and
database interactions (integration testing).
103. Implement a function to check if a string is a
99. How can you improve the performance of a React
palindrome. ```javascript function isPalindrome(str) { const
application?
cleanStr = str.toLowerCase().replace(/[\W_]/g, ''); // Remove
○ Techniques include code splitting, lazy
non-alphanumeric characters and underscores const
loading, optimizing renders with
reversedStr = cleanStr.split('').reverse().join(''); return cleanStr
shouldComponentUpdate or React.memo,
=== reversedStr; }
using production builds, and optimizing
network requests.
○ Example: Implementing React.lazy and javascript
Suspense for lazy loading components to Copy code
reduce initial bundle size and improve console.log(isPalindrome('A man, a plan, a
loading times. canal. Panama')); // Output: true
100. What are the best practices for version control in ```
full-stack development?
○ Best practices include using Git for version
control, branching strategies (e.g., GitFlow), 104. Write a function to find the maximum sum of a
commit messages conventions, pull request contiguous subarray. ```javascript function
reviews, and maintaining a clean project maxSubarraySum(nums) { let maxSum = nums[0]; let
history. currentSum = nums[0];
○ Example: Using feature branches and pull
requests in GitHub to manage collaborative
javascript
development and code reviews.
Copy code
for (let i = 1; i < nums.length; i++) {
These questions delve deeper into various aspects of full-stack
currentSum = Math.max(nums[i],
development, covering deployment, cloud computing,
architecture, testing, and performance optimization. Each currentSum + nums[i]);
question provides insights into essential concepts and practices maxSum = Math.max(maxSum, currentSum);
necessary for building robust and scalable web applications. If }
you have more specific topics or questions in mind, feel free to
ask! return maxSum;
}
3.5
3.5
156.
continue
perl
Copy code
ChatGPT
- **State Management Libraries**: Use libraries
like Redux or MobX for predictable state
Certainly! Let's continue with more scenario-based questions
containers, especially when managing complex and miscellaneous topics related to MERN stack, full-stack
state or sharing state across multiple development, and relevant technologies:
components.
157. Discuss the differences between functional
csharp components and class components in React. -
Copy code Functional Components:
Example with Redux: ○ Introduced in React 16.8 with Hooks.
```javascript ○ Written as plain JavaScript functions.
// Redux store setup ○ Use functional syntax (useState,
import { createStore } from 'redux'; useEffect, etc.) to manage state and
import rootReducer from './reducers'; lifecycle.
○ Lightweight and easier to read/write.
○ Promote separation of concerns and
const store = createStore(rootReducer);
reusability through custom hooks. Example:
return ( markdown
Copy code
<div>
- **sessionStorage**:
{data && <p>{data.message}</p>}
</div>
csharp options: {
Copy code presets: ['@babel/preset-env',
- **Storage Duration**: Data persists only for '@babel/preset-react'],
the duration of the page session. Once the },
session ends (e.g., tab or browser closure), },
data is cleared. },
- **Scope**: Data is limited to the current {
tab or window. It is not shared across test: /\.css$/,
different tabs or windows. use: ['style-loader', 'css-loader'],
- **Usage**: Ideal for storing temporary data },
such as state or form data that is relevant {
only within a single browsing session. test: /\.(png|svg|jpg|gif)$/,
- **API**: Accessed using `sessionStorage` use: ['file-loader'],
object in JavaScript with similar methods },
(`setItem`, `getItem`, `removeItem`, `clear`). ],
Example usage: },
```javascript plugins: [
// Store data in sessionStorage // Add plugins for production
sessionStorage.setItem('token', 'abc123'); optimization, environment variables, etc.
],
// Retrieve data from sessionStorage devServer: {
const token = contentBase: './dist',
sessionStorage.getItem('token'); hot: true,
console.log(token); // Output: abc123 },
``` };
```
184. How do you ensure data integrity in a distributed ● Controlled Components: Use controlled
database system? components to manage form state.
● Validation Libraries: Utilize libraries like Yup, Formik,
● Replication: Use of replicas across nodes to ensure or custom validation logic.
availability and fault tolerance. ● Error Handling: Display error messages based on
● Consistency Models: Implement strong consistency validation results.
models or eventual consistency based on application ● Real-Time Validation: Implement real-time validation
needs. using onChange events.
● Transactions: Ensure atomicity, consistency, ● Submission Handling: Prevent form submission on
isolation, and durability (ACID properties) where validation errors.
applicable.
● Conflict Resolution: Implement conflict resolution
189. Explain the role of CDN (Content Delivery Network) in
strategies for concurrent updates.
improving web application performance.
● Monitoring and Auditing: Regular monitoring and
auditing of data across distributed nodes.
● Content Distribution: Distributes content
● Data Partitioning: Use of sharding techniques to
geographically closer to users, reducing latency.
distribute data and reduce latency.
● Caching: Caches static content like images, CSS,
and JavaScript files to improve load times.
185. Explain the concept of eventual consistency in NoSQL ● Scalability: Offloads bandwidth and reduces load on
databases. origin servers.
● Security: Provides DDoS protection and mitigates
● Definition: NoSQL databases prioritize availability other security threats.
and partition tolerance over strong consistency. ● Analytics: Offers insights into traffic patterns and
● Characteristics: Data may be inconsistent user behavior.
temporarily but will converge to a consistent state
eventually.
190. How do you implement authentication using OAuth in
● Use Cases: Suitable for applications where real-time
a MERN stack application?
consistency is less critical than availability and
partition tolerance.
● OAuth Flow: Use OAuth libraries like Passport.js to
● Examples: DynamoDB, Cassandra, Riak.
implement OAuth authentication.
● Setup OAuth Provider: Register application with
186. How can you improve the performance of a MongoDB OAuth provider (Google, Facebook, etc.) to obtain
database? client ID and client secret.
● Client-Side Integration: Implement OAuth login
● Indexes: Create appropriate indexes for queries to buttons and handle redirection to OAuth provider.
improve query performance. ● Server-Side Integration: Verify OAuth tokens on the
● Sharding: Distribute data across multiple shards to server and create a session for authenticated users.
improve scalability and throughput. ● Persistent Sessions: Store user information in
● Query Optimization: Use aggregation pipelines, session or database for persistent login sessions.
hints, and covered queries to optimize queries.
● Hardware Considerations: Use SSDs for storage
191. Discuss the principles of responsive design in web
and ensure adequate RAM for working set size.
development.
● Monitoring and Profiling: Regularly monitor
performance using MongoDB's profiling tools.
● Flexible Layouts: Use fluid grids and flexible images
to adapt to different screen sizes.
187. Discuss the differences between GraphQL ● Media Queries: Implement CSS media queries to
subscriptions and WebSockets. apply styles based on viewport dimensions.
● Viewport Meta Tag: Configure viewport meta tag to
● GraphQL Subscriptions: control layout on mobile browsers.
○ Purpose: Facilitate real-time data updates ● Flexible Images and Media: Use max-width:
from the server to the client. 100% to ensure images and media scale with their
○ Integration: Built into the GraphQL schema
containers.
as special types (Subscription type). ● Testing: Test designs across various devices and
○ Protocol: Uses HTTP and WebSocket resolutions to ensure responsiveness.
protocols for bidirectional communication.
● WebSockets:
192. How do you handle memory leaks in a Node.js ● Flexibility: Facilitates technology diversity and
application? independent deployment of services.
● Fault Isolation: Limits impact of failures to specific
● Memory Profiling: Use tools like Node.js Profiler or services, enhancing overall system reliability.
Chrome DevTools to identify memory leaks. ● Team Autonomy: Empowers teams to work
● Heap Dump Analysis: Analyze heap dumps to independently on smaller, focused services.
identify objects consuming excess memory. ● Easier Maintenance: Simplifies updating and
● EventEmitter Limits: Use setMaxListeners() to evolving individual services without impacting others.
avoid EventEmitter memory leaks.
● Memory Management: Implement proper memory 197. How do you handle database migrations in MongoDB?
management practices such as releasing unused
resources. ● Manual Approach:
● Testing and Monitoring: Monitor application memory ○ Use scripts to modify schema or data
usage and conduct regular tests to identify and fix directly.
leaks. ● Automated Approach:
○ Use migration libraries or tools (like
193. Explain the differences between bundling and mongeez) that manage migrations through
minification of JavaScript files. versioned scripts.
● Bundling: 3.5
○ Purpose: Combines multiple JavaScript
files into a single bundle. continue upto 200
○ Benefits: Reduces the number of HTTP
requests and improves load times. ChatGPT
○ Tools: Webpack, Parcel, Rollup.
● Minification: Certainly! Let's continue with the next set of questions:
○ Purpose: Removes unnecessary
characters (whitespace, comments) to
198. Explain the principles of DRY (Don't Repeat Yourself)
reduce file size.
in software development.
○ Benefits: Reduces file size and improves
download speed.
○ Tools: UglifyJS, Terser, Google Closure ● Elimination of Redundancy: Avoid duplicating code
Compiler. or logic to maintain a single source of truth.
● Modularity: Encourage modular design to promote
reusability of components or functions.
194. What are the benefits of using Next.js in React
● Maintenance: Simplify maintenance by updating a
applications?
single piece of code that affects multiple instances.
● Readability and Consistency: Improve code
● Server-Side Rendering (SSR): Built-in support for readability and consistency by reducing redundant
SSR, improving SEO and initial load times. code.
● Zero Configuration: Requires minimal setup, ● Abstraction: Use abstraction to generalize common
providing a streamlined development experience. patterns and avoid repetition.
● Automatic Code Splitting: Optimizes bundle size
and load times through automatic code splitting.
199. What are the key metrics you would monitor in a web
● Static Site Generation (SSG): Supports SSG for
application performance dashboard?
pre-rendering pages at build time.
● API Routes: Simplifies API integration by providing
built-in API routes. ● Response Time: Measure how long it takes to load
and interact with pages.
● Throughput: Track the number of requests
195. How do you implement server-side rendering (SSR) in
processed per unit of time.
a Node.js application?
● Error Rate: Monitor the percentage of requests that
result in errors.
● Choose a Framework: Use frameworks like Next.js, ● CPU and Memory Usage: Keep an eye on server
Nuxt.js (for Vue), or custom implementations. resource consumption.
● Server Configuration: Set up server-side logic to ● Latency: Measure the time taken for data to travel
render React/Vue components on the server. from one point to another.
● Routing: Define routes and handle requests to render ● Traffic: Monitor the number of users and sessions on
corresponding components. the site.
● Data Fetching: Fetch initial data on the server using ● Database Performance: Track query execution times
lifecycle hooks or async methods. and connection pool usage.
● Hydration: Send rendered HTML to the client and ● API Performance: Monitor performance of third-party
hydrate it into a fully interactive application. APIs or internal services.
● Browser-Side Metrics: Monitor client-side
196. Discuss the benefits of using a microservices performance metrics like load times and rendering.
architecture in a web application.
200. How do you ensure backward compatibility when
● Scalability: Enables independent scaling of services deploying new features in a web application?
based on demand.
● Versioning: Use versioning for APIs and major
application updates to maintain compatibility.
● Feature Flags: Implement feature toggles to
enable/disable new features selectively.
● API Contracts: Maintain stable API contracts to
ensure existing integrations continue to function.
● Deprecation Notices: Provide advance notice and
deprecation schedules for outdated features.
● Testing: Conduct thorough regression testing to
ensure new features don't break existing functionality.
● User Communication: Communicate changes and
updates clearly to users and stakeholders.