MERN Interview Questions by Shilpi
MERN Interview Questions by Shilpi
5. How does React handle components? Explain the component lifecycle methods.
React manages components as self-contained units that encapsulate UI and behavior.
Components have a lifecycle consisting of various stages:
- Mounting: When a component is created and inserted into the DOM.
- Updating: When a component's state or props change, triggering a re-render.
7. What are controlled and uncontrolled components in React.js? When would you use each?
Controlled components are React components whose value is controlled by React state.
Changes to the input value are handled by React through state updates. Uncontrolled
components, on the other hand, allow the input value to be controlled by the DOM itself. You
would typically use controlled components when you need to handle the input value
programmatically or validate user input. Uncontrolled components are useful for integrating
with third-party libraries or when you want to delegate the handling of input value to the DOM.
12. What are Higher Order Components (HOCs) in React.js? How do they work?
Higher Order Components (HOCs) are a design pattern in React.js for reusing component
logic. HOCs are functions that take a component as input and return a new component with
additional functionality. They enable cross-cutting concerns such as logging, authentication, or
code reuse to be encapsulated in separate components. HOCs enhance composability and
maintainability by promoting separation of concerns.
13. What is React Router? How do you implement routing in React.js applications?
React Router is a popular routing library for React.js applications that enables client-side
routing and navigation. It provides a declarative API for defining routes and rendering
components based on the current URL. To implement routing in React.js applications using
React Router, you would typically define route configurations using `<Route>` components,
handle navigation using `<Link>` or programmatic navigation, and use features like nested
routes, route parameters, and route guards for more complex routing scenarios.
14. What are Hooks in React.js? How do they differ from class components?
Hooks are a feature introduced in React.js version 16.8 that allow functional components to
use state and other React features without writing a class. Hooks provide a more concise and
functional programming-oriented way of managing component state, lifecycle, and side
effects. Unlike class components, which require extending from `React.Component` and using
lifecycle methods, functional components with hooks can encapsulate stateful logic and side
effects directly within the function body, promoting cleaner and more modular code.
15. Explain the differences between `useState`, `useEffect`, `useContext`, and `useReducer` hooks.
- `useState`: Hook for adding state to functional components.
- `useEffect`: Hook for performing side effects in functional components, such as data fetching
or DOM manipulation.
- `useContext`: Hook for consuming React context within functional components.
16. How do you handle forms in React.js? Explain controlled and uncontrolled form components.
In React.js, forms can be handled using controlled or uncontrolled components. Controlled
components bind form inputs to React state, allowing React to control and validate
input values. This is done by setting the value attribute of the form inputs to state variables and
providing event handlers to update the state when the input values change. Controlled
components provide a single source of truth for form data, making it easier to manage and
validate input values.
On the other hand, uncontrolled components allow the DOM to control the form inputs. Instead
of managing input values through state, you let the DOM handle them directly. Uncontrolled
components are useful for integrating with third-party libraries or when you want to optimize
performance by avoiding unnecessary re-renders.
17. What are the differences between functional components and class components in React.js?
- Functional components: These are simple JavaScript functions that accept props as input
and return React elements to describe the UI. With the introduction of hooks, functional
components can also manage state and have access to lifecycle methods.
- Class components: These are ES6 classes that extend `React.Component` and have their
own internal state and lifecycle methods. Class components were the traditional way of
creating React components before the introduction of hooks.
14. Discuss the differences between Redux and Context API in React.
- Redux is a state management library primarily used for larger applications, providing a
centralized store, predictable state mutations, and middleware support. Context API is a feature
in React for sharing state between components without having to explicitly pass props down
through the component tree. While Context API can be used for state management, Redux
offers more features like time-travel debugging and middleware support.
16. What are some common anti-patterns to avoid when working with Redux?
- Common anti-patterns include:
- Mutating state directly in reducers.
- Using Redux for every piece of state in the application, even when it's not necessary.
- Overusing Redux middleware, which can complicate the codebase unnecessarily.
- Over-reliance on global state, which can lead to spaghetti code.
20. Explain how you would handle complex nested state structures in Redux.
- To handle complex nested state structures, you can use techniques like normalizing the
state shape, breaking down the state into smaller manageable pieces, using selectors to
compute derived data, and organizing reducers hierarchically to mirror the nested state
structure.
1. What is Node.js, and how does it differ from traditional server-side languages?
- Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It allows developers
to run JavaScript code on the server-side, enabling non-blocking, event-driven architecture,
which differs from traditional server-side languages like PHP or Python that follow a blocking I/O
model.
7. Explain the difference between callback functions, promises, and async/await in Node.js.
2. What is RESTful architecture, and how does it relate to Node.js and Express.js?
- RESTful architecture is an architectural style for designing networked applications, typically
using HTTP protocols. It emphasizes stateless communication and resource-based URLs.
Node.js and Express.js are commonly used to implement RESTful APIs due to their flexibility and
ease of handling HTTP requests.
4. What are sessions and cookies? How are they implemented in Express.js?
- Sessions and cookies are mechanisms for maintaining state between HTTP requests.
Sessions are typically stored server-side, while cookies are stored on the client-side. In
Express.js, sessions and cookies can be implemented using middleware like `express-session`
and `cookie-parser`. `express-session` manages user sessions by storing session data on the
server and associating a session ID with each client request, while `cookie-parser` parses
cookies sent by the client and populates `req.cookies` with the cookie data.
Key features of MongoDB include its flexible schema design, support for ad-hoc queries,
scalability through sharding, high availability through replication, rich query language, indexing
the JSON model to provide additional data types and support for more efficient storage and
traversal. Unlike JSON, BSON is binary-encoded, allowing for more compact data representation
composed of field-value pairs, where fields are strings and values can be various data types,
collection to have different structures. A document, on the other hand, is a single record within a
collection.
scalability and performance. It involves splitting a collection into smaller chunks called shards,
A replica set in MongoDB is a group of MongoDB instances that maintain the same data set. It
provides high availability and fault tolerance by replicating data across multiple servers. In the
event of a primary node failure, one of the secondary nodes automatically becomes the new
Indexing in MongoDB is the process of creating data structures to improve the speed of data
retrieval operations. Indexes are essential for efficiently querying large datasets by facilitating
SQL databases are relational databases that store data in tables with predefined schemas
and use structured query language (SQL) for data manipulation. NoSQL databases, including
MongoDB, employ flexible data models and do not require predefined schemas. They are
NoSQL databases can be categorized into four main types: document-oriented databases
deployments consist of a single MongoDB instance. Replica sets are groups of MongoDB
instances that maintain the same data set for high availability. Sharded clusters distribute data
MongoDB ensures high availability through features like replica sets, automatic failover, and
data redundancy. Replica sets maintain multiple copies of data across different servers,
allowing for automatic promotion of secondary nodes to primary in case of primary node
failure.
Data modeling in MongoDB involves designing the structure of documents and collections to
reflect the application's data requirements. It includes identifying relationships between data,
optimizing document structure for efficient querying, and considering factors like scalability
and performance.
GridFS is a specification for storing and retrieving large files in MongoDB. It divides files into
smaller chunks, which are then stored as separate documents in a collection. GridFS is used
when dealing with large binary data, such as images, videos, or files, that exceed the BSON
computations on large datasets. It involves two main stages: the map stage, where data is
processed and transformed into intermediate key-value pairs, and the reduce stage, where the
auditing. Authentication ensures that only authenticated users can access the database, while
authorization controls access rights and privileges. Encryption protects data both at rest and in
transit, and auditing tracks database activities for compliance and security purposes.
documents to compute aggregated results. It allows for complex data analysis tasks like
grouping, filtering, and computing aggregate functions such as sum, average, and count.
MongoDB supports various types of queries, including CRUD (Create, Read, Update, Delete)
operations, aggregation queries, geospatial queries, text search queries, and MapReduce
queries.
The MongoDB profiler is a diagnostic tool that monitors database operations to identify
performance bottlenecks and optimize query performance. It collects data on query execution
times, index usage, and other metrics to help developers analyze and improve application
performance.
within a single replica set or sharded cluster. Transactions ensure data integrity and
MongoDB has some limitations, including lack of support for ACID transactions across
multiple documents and collections in distributed environments, limited support for JOIN
operations, and potential performance issues with large datasets and complex queries.
Replication Factor in MongoDB refers to the number of copies of data maintained across
different servers or nodes within a replica set. It determines the level of data redundancy and
fault tolerance in the system. A higher replication factor increases fault tolerance but also
MongoDB can be monitored using various tools and techniques, including the MongoDB
Monitoring Service (MMS), built-in monitoring features like mongostat and db.stats(),
third-party monitoring solutions, and integrating MongoDB with external monitoring and
alerting systems.
Backup strategies in MongoDB include regular backups using tools like mongodump or
filesystem snapshots, continuous backups using MongoDB Atlas Backup service or third-party
backup solutions, and offsite backups to remote storage for disaster recovery purposes.
Read preference in MongoDB determines which replica set members are eligible to handle
read operations. It allows developers to specify preferences for reading data from primary or
secondary nodes based on factors like data consistency, latency, and load distribution.
WiredTiger is the default storage engine for MongoDB since version 3.2. It offers significant
MongoDB Compass is a graphical user interface (GUI) tool for MongoDB that provides a visual
interface for performing database operations, managing data, creating queries, and analyzing
database performance.
multiple read operations to occur simultaneously but restricts write operations to ensure data
Write Concern in MongoDB specifies the level of acknowledgment required from the server for
"unacknowledged," "journaled," and "replica acknowledged," which determine the durability and