🌟 Introduction
🚀 Ready to crack your next MERN Stack Developer interview?
The MERN stack – MongoDB, Express.js, React.js, and Node.js – is one of the most in-demand full stack development technologies today. Whether you are a fresher aiming for your first developer role or an experienced professional targeting top MNCs and startups, mastering MERN concepts is essential.
In this guide, we have compiled the top MERN Stack Developer interview questions and answers explained clearly with examples. From database integration, REST APIs, React hooks, to Node.js async patterns, this list covers everything you need for your interview preparation.
👉 Also explore our Top 75 DBMS Interview Questions and Answers to strengthen your database fundamentals alongside MERN.
💡 Revise thoroughly and boost your confidence to ace your upcoming interviews with ease.
Â
1. What is MERN Stack?
Answer: MERN stack is a combination of MongoDB, Express.js, React.js, and Node.js technologies to build full-stack web applications.
- MongoDB: NoSQL database
Â
- Express.js: Backend framework for Node.js
Â
- React.js: Frontend JavaScript library
Â
- Node.js: JavaScript runtime environment
Â
Example: A MERN app stores user data in MongoDB, creates REST APIs with Express.js, renders UI with React, and runs the server with Node.js.
2. Why is MERN preferred over MEAN stack?
Answer: In MERN, React.js is used instead of Angular. React uses virtual DOM for better performance, is component-based, and easier to integrate with Node APIs. Developers prefer JSX and unidirectional data flow prefers MERN.
3. Explain virtual DOM in React.
Answer: Virtual DOM is a lightweight copy of the real DOM. When a state changes, React updates only the changed parts by comparing virtual DOM with real DOM using a diffing algorithm for performance.
Example: Updating a user’s profile name rerenders only that specific DOM node instead of the entire page.
4. What is JSX in React?
Answer: JSX stands for JavaScript XML. It allows writing HTML-like syntax inside JavaScript code, which React converts to React.createElement() calls during compilation.
Example:
const element = <h1>Hello, User!</h1>;
5. Explain lifecycle methods in React class components.
Answer: Key lifecycle methods:
- componentDidMount(): Runs after component mounts
Â
- componentDidUpdate(): Runs after updates
Â
- componentWillUnmount(): Runs before unmounting
Â
6. What are functional components and hooks?
Answer: Functional components are plain JavaScript functions returning JSX. Hooks like useState, useEffect allow them to use state and lifecycle features.
Example:
import React, { useState } from ‘react’;
function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count+1)}>Count {count}</button>
}
7. Explain useEffect hook.
Answer: useEffect is used for side effects like API calls, DOM updates. It runs after every render by default or only when dependencies change.
Example:
useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]);
8. What is Express.js used for?
Answer: Express.js simplifies creating REST APIs with routing, middleware, and simplified HTTP handling.
Example:
app.get(‘/users’, (req, res) => {
  res.send(‘User list’);
});
9. Explain middleware in Express.
Answer: Middleware are functions with access to request, response, and next. Used for logging, authentication, parsing JSON, etc.
Example:
app.use(express.json());
10. How do you connect MongoDB with Node.js using Mongoose?
Answer:
const mongoose = require(‘mongoose’);
mongoose.connect(‘mongodb://localhost:27017/testdb’, {
  useNewUrlParser: true, useUnifiedTopology: true
})
.then(() => console.log(‘Connected to DB’))
.catch(err => console.log(err));
11. What is Mongoose schema and model?
Answer:
- Schema: Defines structure of MongoDB documents
Â
- Model: Wrapper for schema to interact with MongoDB collections
Â
Example:
const userSchema = new mongoose.Schema({
  name: String, age: Number
});
const User = mongoose.model(‘User’, userSchema);
12. How to create REST API in Express.js?
Answer:
app.get(‘/api/users’, (req, res) => { res.send(users); });
app.post(‘/api/users’, (req, res) => { users.push(req.body); res.send(req.body); });
13. What is prop drilling in React?
Answer: Prop drilling refers to the situation in React where you pass data from a parent component down to deeply nested child components through multiple intermediate components, even if some of them do not need the data themselves.
Explanation:
- In React, data flows from parent to child via props.
Â
- When a deeply nested child needs data, but it is stored in a top-level component, you have to pass it through all the components in between, even if those intermediate components do not use it themselves.
14. What is the Context API in React?
Answer: The Context API is a feature in React that allows you to share data (state) globally across components without having to pass props manually at every level (avoiding prop drilling).
Why is it used?
To share global data such as:
- Theme (light/dark mode)
Â
- User authentication status
Â
- Language preferences
Â
- Any state needed by multiple components
Â
To avoid prop drilling, where props are passed through intermediate components unnecessarily.
Example:
const UserContext = React.createContext();
<UserContext.Provider value={user}><Profile /></UserContext.Provider>
15. How to handle forms in React?
Answer: Using controlled components with state to handle input values and events.
Example:
const [name, setName] = useState(”);
<input value={name} onChange={e => setName(e.target.value)} />
16. Explain CRUD operations using Mongoose.
Answer:
- Create: User.create({name:’John’})
Â
- Read: User.find()
Â
- Update: User.updateOne({name:’John’}, {$set:{age:30}})
Â
- Delete: User.deleteOne({name:’John’})
Â
17. What is useState hook?
Answer: The useState hook is a built-in React hook that allows functional components to have state variables, enabling them to store and manage data that changes over time.
Explanation:
- Before hooks, only class components had state using this.state.
- With useState, functional components can now hold state, making them more powerful and replacing class components in many cases.
Example:
const [state, setState] = useState(initialValue);
state – The current state value.
setState – A function to update the state.
initialValue – The initial value of the state variable.
18. Explain routing in Express.js.
Answer: Routing in Express.js refers to defining the way an application responds to client requests (GET, POST, PUT, DELETE, etc.) for specific endpoints (URLs) and HTTP methods.
Explanation:
Routing determines how your server handles incoming requests based on:
- URL path (e.g. /users, /api/products/1)
Â
- HTTP method (GET, POST, PUT, DELETE)
Â
19. What is React Router?
Answer: React Router is a standard routing library for React that enables you to handle navigation and rendering of different components based on the URL in single-page applications (SPAs).
Why is it used?
- React by default is a single-page application – it renders one HTML page.
- React Router enables you to create multiple views (pages) within the SPA, allowing seamless navigation without full page reloads.
20. Difference between PUT and PATCH.
Answer:
- PUT: Replaces entire resource.
Â
- PATCH: Updates specific fields.
21. What is Redux?
Answer: Redux is a state management library for JavaScript apps, mainly used with React to manage global state in a predictable way using store, actions, and reducers.
Example: Counter app where increment/decrement actions update the global store, and components subscribe to the state.
22. Explain store, actions, and reducers in Redux.
Answer:
- Store: Holds the entire app state
Â
- Actions: Plain JS objects describing what happened
Â
- Reducers: Functions that specify how state changes in response to actions
Â
23. What is thunk middleware in Redux?
Answer: Thunk middleware lets your Redux actions do async tasks (like API calls) before updating the store, instead of only sending plain objects directly.
Explanation:
- In Redux, by default, action creators return plain JavaScript objects (actions).
Â
- Redux Thunk middleware extends this to allow action creators to return functions.
Â
- The returned function receives dispatch and getState as arguments, enabling:
Â
- Dispatching multiple actions (e.g. loading, success, error)
- Performing asynchronous operations like API calls
- Accessing the current state if needed
Example With Thunk:
// Action creator with thunk (asynchronous)
const fetchData = () => {
  return (dispatch, getState) => {
    dispatch({ type: ‘FETCH_DATA_REQUEST’ });
    fetch(‘https://api.example.com/data’)
      .then(response => response.json())
      .then(data => {
        dispatch({ type: ‘FETCH_DATA_SUCCESS’, payload: data });
      })
      .catch(error => {
        dispatch({ type: ‘FETCH_DATA_FAILURE’, payload: error });
      });
  };
};
24. Difference between localStorage and sessionStorage.
Answer:
Feature | localStorage | sessionStorage |
Persistence / Expiry | Data is stored with no expiration time. It persists even after the browser is closed and reopened. | Data is stored per session. It is cleared when the page session ends, i.e., when the browser tab is closed. |
Scope | Available across all tabs and windows from the same origin (domain + protocol + port). | Available only in the same tab/window where it was created. Other tabs cannot access it, even if they are from the same origin. |
Storage Limit | Usually around 5-10 MB per origin (varies by browser). | Similar limit as localStorage (5-10 MB), but scoped to each tab session. |
Use Case | Useful for storing data that needs to be available long-term, e.g. user preferences, theme settings, login tokens (with caution). | Useful for storing data that should be available only for a single session, e.g. temporary form data, shopping cart in tab. |
Clearing Data | Data remains until explicitly cleared by JavaScript or browser settings. | Data is automatically cleared when the browser tab or window is closed. |
API usage | Same API for both: setItem, getItem, removeItem, clear. | Same API as localStorage. |
Example | js localStorage.setItem(“name”, “Brajesh”); console.log(localStorage.getItem(“name”)); | js sessionStorage.setItem(“name”, “Brajesh”); console.log(sessionStorage.getItem(“name”)); |
Â
25. What is CORS?
Answer: Cross-Origin Resource Sharing. Controls how resources are shared between different origins. Needed in MERN when React (frontend) requests Node APIs (backend) hosted on different ports.
26. How to enable CORS in Express.js?
Answer:
const cors = require(‘cors’);
app.use(cors());
27. Explain promises in Node.js.
Answer: A Promise is like an assurance note: “I promise to give you the result later, either success or failure, and you can plan what to do in both cases.”
Explanation:
- A Promise is in one of three states:
Â
- Pending: Initial state; neither fulfilled nor rejected.
Â
- Fulfilled: Operation completed successfully, and the promise has a resulting value.
Â
- Rejected: Operation failed, and the promise has a reason (error).
Â
- Pending: Initial state; neither fulfilled nor rejected.
- Promises are used to handle asynchronous operations in a cleaner way compared to callbacks.
Example:
Create a Promise
const myPromise = new Promise((resolve, reject) => {
  // asynchronous operation
  let success = true;
  if (success) {
    resolve(“Operation Successful”);
  } else {
    reject(“Operation Failed”);
  }
});
Consuming a Promise
myPromise
  .then(result => {
    console.log(“Success:”, result);
  })
  .catch(error => {
    console.log(“Error:”, error);
  });
28. Difference between callbacks and promises.
Answer:
Feature | Callbacks | Promises |
Definition | A function passed as an argument to another function to be executed after an asynchronous operation completes. | An object representing the eventual completion or failure of an asynchronous operation. |
Syntax style | Nested functions; can lead to callback hell (deep nesting). | Chained .then() and .catch(), avoiding deep nesting. |
Error handling | Requires error-first callback convention (e.g. function(err, data) {}). Multiple error handlers in nested callbacks are harder to manage. | Uses .catch() method to handle errors in a clean way. Errors bubble down the promise chain. |
Readability | Harder to read and maintain for multiple sequential async operations due to nesting. | More readable and maintainable due to chaining and flattening of asynchronous flows. |
Return value | Cannot return values directly from an async callback to its outer function. | Promises can return another promise, allowing chaining of asynchronous operations. |
Multiple async operations | Complex to manage parallel or sequential operations. | Easier with Promise.all(), Promise.race(), and chaining. |
Example | js function getData(callback) { db.query(sql, function(err, result) { if (err) callback(err); else callback(null, result); }); } | js function getData() { return new Promise((resolve, reject) => { db.query(sql, (err, result) => { if (err) reject(err); else resolve(result); }); }); } getData().then(data => console.log(data)).catch(err => console.log(err)); |
29. What is async/await in Node.js?
Answer: async/await allows you to write asynchronous code as if it were synchronous, improving readability and reducing complexity in Node.js applications.
Explanation:
async keyword:
- Used to declare a function as asynchronous.
- Always returns a Promise.
- Â
Example:
async function myFunction() {
  return “Hello”;
} // myFunction() returns a Promise that resolves to “Hello”
Â
await keyword:
- Used inside async functions to pause execution until a Promise is resolved or rejected.
- Makes the code wait for the result before moving to the next line, thus writing asynchronous code in a synchronous style.
Example:
async function fetchData() {
  try {
    const response = await fetch(“https://api.example.com/data”);
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.log(“Error:”, error);
  }
}
fetchData();
30. How to handle errors in Express.js?
Answer: Express has built-in error-handling middleware that takes four arguments.
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send(‘Something broke!’);
});
Key points:
- err is the error object passed from routes or other middleware.
Â
- If any middleware calls next(err), Express jumps to this error handler.
Â
🌟 Conclusion
💡 Strong MERN stack knowledge opens doors to high-paying full stack developer roles in product-based companies, startups, and MNCs. This curated list of top MERN Stack Developer interview questions and answers with examples ensures you revise all major topics effectively – from React state management to Express middleware, Node.js modules to MongoDB aggregation.
👉 Don’t forget to check out our Top JavaScript Interview Questions to polish your core JavaScript skills, essential for MERN development.
🔖 Keep practicing, build real projects, and stay updated with the latest MERN stack advancements to stand out as a strong full stack developer in your upcoming interviews.