Top 50 MERN Stack Interview Questions with Sample Code

Top 50 MERN Stack Interview Questions with Sample Code ,The MERN stack is a popular choice for developing modern web and mobile applications. It is composed of MongoDB, Express, React, and Node.js, offering a powerful combination for building fast, scalable applications. In this blog post, we’ll cover 50 common MERN stack interview questions, along with sample code to help you prepare for interviews and improve your skills.

Table of Contents


Q1: How does React work?

React creates a virtual DOM. When the state of a component changes, it first runs a “diffing” algorithm that identifies what has changed in the virtual DOM. Then, it performs a reconciliation process, updating the real DOM with the results of the diff. Top 50 MERN Stack Interview Questions with Sample Code

Q2: What is props in React?

Props are inputs to a React component, passed from parent components. They are immutable, meaning they cannot be changed by the component receiving them.

Example:

function ParentComponent() {
  return <ChildComponent name="John" />;
}

function ChildComponent(props) {
  return <p>Hello, {props.name}!</p>;
}

Q3: What Is Replication in MongoDB?

Replication in MongoDB refers to the process of synchronizing data across multiple servers, providing redundancy and ensuring high availability.


Q4: What are Higher-Order Components in React?

A Higher-Order Component (HOC) is a function that takes a component and returns a new component.

Example:

function withLoading(Component) {
  return function WithLoading({ isLoading, ...props }) {
    if (isLoading) {
      return <div>Loading...</div>;
    }
    return <Component {...props} />;
  };
}

Q5: What do you mean by Asynchronous API?

In Node.js, asynchronous APIs allow the server to perform non-blocking operations. The server doesn’t wait for one operation to complete before moving on to the next one. Top 50 MERN Stack Interview Questions with Sample Code


Q6: What is Callback Hell?

Callback hell occurs when multiple asynchronous functions are nested, leading to deeply indented and difficult-to-maintain code.

Example:

fs.readFile('file1.txt', (err, data1) => {
  fs.readFile('file2.txt', (err, data2) => {
    fs.readFile('file3.txt', (err, data3) => {
      console.log(data1, data2, data3);
    });
  });
});

Q7: What is Reconciliation in React?

Reconciliation is the process React uses to update the DOM efficiently by comparing the current and previous virtual DOMs and making the necessary updates.


Q8: Does MongoDB Support Foreign Key Constraints?

No, MongoDB doesn’t support foreign key constraints. Instead, developers can use references and manual data integrity checks.


Q9: How Node.js prevents blocking code?

Node.js uses callbacks, ensuring the event loop doesn’t block while waiting for I/O operations.


Q10: How can you achieve transactions and locking in MongoDB?

MongoDB supports atomic operations within a single document, which can act as transactions.

Example:

const session = await mongoose.startSession();
session.startTransaction();
try {
  await User.create([{ name: 'John' }], { session });
  await session.commitTransaction();
} catch (error) {
  await session.abortTransaction();
}
session.endSession();

Q11: How does Node.js handle child threads?

Node.js is single-threaded but uses background threads for I/O operations. It manages concurrency through the event loop and worker threads.


Q12: How to avoid Callback Hell in Node.js?

You can avoid callback hell by using promises, async/await, and modularizing your code.


Q13: If Node.js is single-threaded, how does it handle concurrency?

Node.js uses multiple threads under the hood, offloading I/O operations, while the main event loop handles execution.


Q14: What are Pure Components in React?

A PureComponent automatically implements shouldComponentUpdate with a shallow comparison of props and state to optimize performance.

Example:

class MyComponent extends React.PureComponent {
  render() {
    return <div>{this.props.name}</div>;
  }
}

Q15: What are React Hooks?

React Hooks are functions that allow you to use state and lifecycle features in functional components.

Example:

import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

Q16: What is Aggregation in MongoDB?

Aggregation in MongoDB is a framework for transforming and combining data in various ways, like grouping or filtering.


Q17: What is JSX?

JSX is a syntax extension for JavaScript that lets you write HTML-like structures inside your JavaScript code.

Example:

const element = <h1>Hello, World!</h1>;

Q18: What is ReactDOM?

ReactDOM is a package that provides DOM-specific methods for rendering and updating React components in the web browser.

Example:

ReactDOM.render(<App />, document.getElementById('root'));

Q19: What is Sharding in MongoDB?

Sharding in MongoDB is the process of distributing data across multiple servers to handle large datasets and high throughput operations.


Q20: What are Streams in Node.js?

Streams are a sequence of data that can be read or written in chunks, allowing handling of large data sets without consuming too much memory.

Example:

const fs = require('fs');
const readStream = fs.createReadStream('largeFile.txt');
readStream.on('data', chunk => {
  console.log('Received chunk:', chunk);
});

Q21: What is Prop Drilling?

Prop drilling refers to the process of passing props through many layers of components to reach a deeply nested component.


Q22: What is the purpose of key in React?

The key prop helps React identify which items in a list have changed, been added, or removed.

Example:

const items = ['apple', 'banana', 'cherry'];
const listItems = items.map((item, index) => <li key={index}>{item}</li>);

Q23: What is Blocking Code?

Blocking code causes the application to wait for an operation (like an I/O task) to complete before moving on to the next operation.


Q24: What is the difference between ShadowDOM and VirtualDOM?

  • VirtualDOM is a React concept for optimizing DOM updates.
  • ShadowDOM is used for encapsulating a component’s internal structure.

Q25: What’s the Event Loop in Node.js?

The event loop allows Node.js to perform non-blocking I/O operations by offloading tasks to the system kernel whenever possible.


Q26: What’s the difference between a “smart” and “dumb” component?

  • Smart component: Manages state or interacts with the Redux store.
  • Dumb component: Receives data via props and is stateless.

Q27: What is Mongoose?

Mongoose is an ODM (Object Document Mapper) for MongoDB that provides a schema-based solution for modeling application data.

Example:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

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

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

Q28: What is REPL in Node.js?

REPL (Read-Eval-Print Loop) is an interactive environment where you can run JavaScript commands and see their results immediately.


Q29: How to check if an object is an array in JavaScript?

You can use Array.isArray().

Example:

Array.isArray([1, 2, 3]); // true
Array.isArray({}); // false

Q30: What are the two arguments that async.queue takes in Node.js?

  • Task function: The function to execute.
  • Concurrency value: The maximum number of tasks to process concurrently.

Q31: What is the purpose of module.exports in Node.js?

module.exports allows you to expose functions and variables from a module to be used in other files.

Example:

module.exports = function greet(name) {
  return `Hello, ${name}!`;
};

Q32: What are Node.js Buffers?

Buffers are temporary storage areas used to hold data before it is processed or transferred.


Q33: What is a Thread Pool in Node.js?

Node.js uses a thread pool to handle operations like file I/O and DNS queries asynchronously, managed by the libuv library.


Q34: How to make Node.js modules available externally?

You can use module.exports to expose module functions.


Q35: What is the default scope of Node.js application?

The default scope is local to the module, and each module has its own scope.


Q36: Which module is used to serve static files in Node.js?

The express.static middleware is used for serving static files like HTML, CSS, and images.


Q37: What is a Document in MongoDB?

A document in MongoDB is a data structure that stores key-value pairs, similar to a JSON object.

Top 50 MERN Stack Interview Questions with Sample Code


Q38: What is Mongo Shell?

Mongo Shell is an interactive JavaScript shell that allows you to interact with MongoDB instances.


Q39: How do you Delete a Document in MongoDB?

Use deleteOne or deleteMany to delete documents.

Example:

db.users.deleteOne({ name: 'John' });

Q40: What is Scaffolding in Express.js?

Scaffolding refers to creating the basic structure of your application. You can use tools like the Express generator to automate this process.

Top 50 MERN Stack Interview Questions with Sample Code


Q41: What is Routing in Express.js?

Routing determines how an application responds to a request for a specific endpoint, defined by a URL path and HTTP method.

Top 50 MERN Stack Interview Questions with Sample Code


Q42: What is Middleware in Express.js?

Middleware functions are used to modify requests or responses or to perform operations before the final request handler.

Top 50 MERN Stack Interview Questions with Sample Code


Q43: How Can I Authenticate Users in Express?

You can use any authentication strategy like Passport.js or JWT (JSON Web Tokens).


Q44: Which Template Engines Does Express Support?

Express supports many template engines such as EJS, Pug, and Handlebars.


Q45: How Do I Render Plain HTML in Express?

You can use res.sendFile() to send an HTML file or express.static() to serve static files.


Q46: How to Implement JWT Authentication in Express?

You can implement JWT (JSON Web Token) for stateless authentication by using the jsonwebtoken library.


By mastering these concepts and practicing with the sample code provided, you’ll be well-prepared for MERN stack interviews. Top 50 MERN Stack Interview Questions with Sample Code

Top 50 MERN Stack Interview Questions with Sample Code

Creating and nesting components


React apps are made out of components. A component is a piece of the UI (user interface) that has its own logic and appearance. A component can be as small as a button, or as large as an entire page.Top 50 MERN Stack Interview Questions with Sample Code

React components are JavaScript functions that return markup:

function MyButton() {
return (
I’m a button
);
}

React

Programmatic React features:

Hooks – Use different React features from your components.

Components – Built-in components that you can use in your JSX.

APIs – APIs that are useful for defining components.

Directives – Provide instructions to bundlers compatible with React Server Components.

Top 50 MERN Stack Interview Questions with Sample Code

Form Hooks 

Forms let you create interactive controls for submitting information. To manage forms in your components, use one of these Hooks:

  • useFormStatus allows you to make updates to the UI based on the status of the a form.

function Form({ action }) {
async function increment(n) {
return n + 1;
}
const [count, incrementFormAction] = useActionState(increment, 0);
return (
Count: {count}
);
}

function Button() {
const { pending } = useFormStatus();
return (
Submit
);
}

Top 50 MERN Stack Interview Questions with Sample Code