36 practice questions with answers for MERN Stack interviews in Lucknow.
MERN Stack jobs in Lucknow
Lucknow's tech job market is smaller but growing, led by IT-services delivery centres, government-tech projects and start-ups. Many Lucknow candidates target Noida and Gurgaon roles or remote jobs, so interviews follow the NCR pattern.
Below are 36 questions that match the mix of service, product and domain employers hiring mern stack developers in Lucknow.
Solved for LucknowStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
✓ 3 questions free • Unlock the rest in seconds
01
What is the difference between useMemo and useCallback?
useMemo caches the result of a calculation, recomputing only when dependencies change, for example a filtered and sorted list. useCallback caches a function reference, so useCallback(fn, deps) equals useMemo(() => fn, deps). They help when passing values or callbacks to memoized children or as effect dependencies. They have their own cost, so do not wrap everything; the React Compiler can now add this memoization automatically.
When two or more components need the same data, you move that state to their closest common parent and pass it down as props, along with functions to update it. For example, a filter bar and a product list both depend on the selected category, so the page component holds the category state. This keeps one source of truth and avoids components getting out of sync.
03
How do you implement code splitting in a React app?
Use dynamic import with React.lazy, for example const Admin = lazy(() => import('./Admin')), and wrap it in a Suspense boundary with a fallback. Bundlers like Vite then create a separate chunk that loads only when needed. Split by route first, then by heavy components like charts, editors and maps. Preload likely next routes on hover, and check results with a bundle analyser such as rollup-plugin-visualizer.
Each loop iteration goes through phases: timers runs expired setTimeout and setInterval callbacks; pending callbacks runs some deferred system callbacks; poll waits for and runs I/O callbacks; check runs setImmediate callbacks; close callbacks handles events like socket close. Between every callback, Node drains process.nextTick callbacks and then Promise microtasks. Knowing this explains why setImmediate inside an I/O callback always runs before a setTimeout of 0.
05
Group an array of order objects by their status using reduce.
reduce builds an object whose keys are statuses and values are arrays.
const grouped = orders.reduce((acc, order) => {
(acc[order.status] ||= []).push(order);
return acc;
}, {});
// { paid: [...], pending: [...] }
Newer runtimes also offer Object.groupBy(orders, (o) => o.status), which returns the same shape with a null prototype.
06
Tell me about a time you found and fixed a security issue in an application.
Situation: while testing an order history feature, I noticed changing the order id in the URL showed another user's order. Task: fix this insecure direct object reference before release. Action: I added an ownership check in the service layer so queries always filter by the logged-in user's id, wrote tests for cross-user access, and reviewed similar endpoints. Result: we fixed four endpoints and added ownership checks to our review checklist.
07
What is the difference between == and === in JavaScript?
== compares values after type coercion, so 0 == '0' and null == undefined are both true. === compares value and type without coercion, so 0 === '0' is false. Coercion rules are hard to remember and cause subtle bugs, so teams use === everywhere, often enforced by an ESLint rule. A common accepted exception is value == null, which checks for both null and undefined in one step.
08
Some tests pass locally but fail randomly in CI. How do you handle flaky tests?
Rerun to confirm flakiness, then find the cause instead of adding retries. Common causes are shared database state between tests, tests depending on run order, real timers and dates, network calls to real services, and E2E tests using fixed waits instead of waiting for elements. Isolate data per test, mock time and external APIs, use proper async waits, and quarantine a flaky test with a ticket until fixed.
09
Write a unit test for a function that calculates a cart total.
By default Mongoose queries return full documents with change tracking, getters, virtuals and methods like save. Calling .lean() returns plain JavaScript objects, which uses much less memory and is noticeably faster. Use it for read-only endpoints such as lists and API responses. Skip it when you need to modify and save the document, or depend on virtuals and getters unless you add a lean plugin.
11
Write a useDebounce hook and use it for a search input.
CommonJS uses require and module.exports, loads synchronously and is the historic Node default. ES modules use import and export, are statically analysable, support top-level await and enable tree shaking. Node treats .mjs files, or .js files when package.json has type: module, as ESM. Modern Node versions can even require synchronous ES modules, but mixing systems still needs care, so new MERN projects usually pick ESM throughout.
Docker packages each service with its runtime and dependencies into an image so it runs the same on every machine. Typically the Express API gets an image built from a Node base, the React app is built and served by Nginx, and MongoDB runs from the official image locally while production often uses MongoDB Atlas. docker compose starts all services with one command, with networks and volumes for persistent data.
14
Your Node.js API runs on an 8-core server but CPU monitoring shows only one core busy. What do you do?
A Node process runs JavaScript on a single thread, so one instance uses about one core. Run multiple instances: PM2 in cluster mode with -i max, the cluster module, or several containers behind a load balancer such as Nginx. Because instances do not share memory, move sessions, caches and rate-limit counters to Redis, and make sure the app is stateless so any instance can serve any request.
15
Your MERN app works on your laptop but crashes after deployment to a server. How do you troubleshoot?
Read the server logs first. Common causes are missing environment variables, a different Node version, the database host or IP allowlist blocking the server, hardcoded localhost URLs, wrong PORT handling, devDependencies missing in production, case-sensitive file names on Linux, and the frontend API base URL pointing to localhost. Reproduce with the same Node version or a Docker image, and validate config at startup.
16
Props are being passed through five levels of components that do not use them. How would you refactor?
This is prop drilling. First try component composition: pass ready-made elements as children or props so intermediate components do not need the data. If many distant components need it, create a Context with a custom hook like useAuth. For complex or frequently updated shared state, use a store such as Zustand or Redux Toolkit with selectors so only interested components re-render.
17
Write a production Dockerfile for a Node.js Express API.
Keep the image small and run as a non-root user.
FROM node:22-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY package*.json ./
RUN npm ci --omit=dev
COPY src ./src
USER node
EXPOSE 5000
CMD ["node", "src/server.js"]
Copying package files first lets Docker cache the dependency layer, so code changes rebuild quickly. Add a .dockerignore with node_modules and .env.
18
How do you protect certain routes in React so that only logged-in users can access them?
Create a ProtectedRoute or layout component that reads auth state from context. If the user is not authenticated, return <Navigate to='/login' replace state={{ from: location }} />, otherwise render the Outlet or children. Show a loader while the session check is pending to avoid flicker. Remember that this is only for user experience; real protection must happen on the Express API by verifying tokens on every request.
19
Write an Express middleware that verifies a JWT from the Authorization header.
Check-then-insert is a race condition: two concurrent requests both see no user and both insert. The real fix is a unique index on email, normalised to lowercase, so the database rejects the second insert with error code 11000. Catch that error and return 409 Conflict. Clean up existing duplicates before building the index, otherwise index creation fails.
21
Tell me about a time you disagreed with a teammate about an API design decision.
Situation: a frontend teammate wanted one endpoint returning the entire dashboard, while I preferred separate resource endpoints. Task: we needed a decision before sprint planning. Action: I listed trade-offs, measured payload size and call counts for both, and we agreed on resource endpoints plus one aggregated summary endpoint for the first screen. Result: the dashboard loaded faster and the API stayed reusable for the mobile app.
22
What is PM2 and why is it used to run Node.js in production?
PM2 is a process manager for Node.js. It keeps the app alive by restarting it after crashes, runs multiple instances in cluster mode to use all CPU cores, supports zero-downtime reloads with pm2 reload, manages logs and starts apps on server boot. Configuration lives in an ecosystem.config.js file. On container platforms like Kubernetes, the orchestrator often replaces PM2's restart and scaling role.
23
What are Mongoose middleware hooks and give a common use case.
Mongoose middleware are functions that run before or after operations such as save, validate, deleteOne, findOneAndUpdate and aggregate. A classic pre-save hook hashes a password only if it was modified: if (!this.isModified('password')) return; this.password = await bcrypt.hash(this.password, 12). Post hooks are used for logging or syncing. Note that query middleware like findOneAndUpdate does not trigger save hooks.
24
Should you store a JWT in localStorage or in an httpOnly cookie?
localStorage is readable by any JavaScript on the page, so an XSS bug can steal the token. An httpOnly, Secure cookie cannot be read by JavaScript, which protects against token theft through XSS, but cookies are sent automatically, so you must defend against CSRF with SameSite=Lax or Strict and CSRF tokens where needed. A common pattern keeps the refresh token in an httpOnly cookie and the access token in memory.
25
Your app needs user, editor and admin roles with different permissions. How would you implement it?
Store a role, or a list of permissions, on the user document and include it in the token or load it in the auth middleware. Write an authorize middleware that checks allowed roles or permissions per route, for example authorize('admin'). Add ownership checks in services, such as an editor editing only their own articles. In React, hide buttons by role for user experience, but always enforce rules on the server.
26
How do class component lifecycle methods map to hooks?
componentDidMount maps to useEffect with an empty dependency array. componentDidUpdate maps to useEffect with specific dependencies. componentWillUnmount maps to the cleanup function returned from useEffect. shouldComponentUpdate is roughly React.memo, and getDerivedStateFromProps is usually replaced by computing values during render. The mindset shifts from lifecycle moments to synchronising with external systems whenever certain values change.
27
Tell me about a time you had to deliver a frontend feature under a tight deadline.
Situation: a client demo was moved two days earlier and our filters page was half done. Task: deliver a working version in time. Action: I agreed a reduced scope with the lead, reused existing components, built the three most-used filters first and wrote quick tests for them, and kept the team updated each evening. Result: the demo went well and the remaining filters shipped in the next sprint.
28
What is the difference between process.nextTick, setImmediate and setTimeout(fn, 0)?
process.nextTick queues a callback to run right after the current operation, before Promise microtasks and before the event loop continues. setImmediate runs in the check phase after poll. setTimeout with 0 runs in the timers phase once at least about 1 ms has passed. Overusing nextTick recursively can starve I/O, so setImmediate is the safer way to defer heavy work.
29
Compress a large file with gzip using streams in Node.js.
Wrap risky sections in error boundaries. An error boundary catches rendering errors in its subtree and shows fallback UI instead of unmounting the whole app. React still requires a class with getDerivedStateFromError and componentDidCatch, or you can use the react-error-boundary package. Place boundaries around each widget and the route level, log errors to monitoring, and offer a retry. They do not catch errors in event handlers or async code.
31
Write a docker-compose file to run a MERN app locally.
Three services on one network:
services:
mongo:
image: mongo:8
volumes:
- mongo-data:/data/db
api:
build: ./server
environment:
MONGO_URI: mongodb://mongo:27017/shop
JWT_SECRET: dev-secret
ports:
- "5000:5000"
depends_on:
- mongo
web:
build: ./client
ports:
- "8080:80"
depends_on:
- api
volumes:
mongo-data:
The API reaches the database through the service name mongo.
32
What is the difference between a shallow copy and a deep copy?
A shallow copy duplicates only the top level, so nested objects are still shared references. Spread syntax and Object.assign make shallow copies. A deep copy duplicates every nested level. structuredClone(obj) is the built-in way in modern browsers and Node.js and supports Dates, Maps and Sets, while JSON.parse(JSON.stringify(obj)) loses functions, undefined and Dates. In React state updates, shallow copies of each changed level are usually enough.
33
How do you implement graceful shutdown for a Node.js API during deployments?
Listen for SIGTERM and SIGINT. When received, stop accepting new connections with server.close(), let in-flight requests finish, close database connections with mongoose.connection.close() and other resources, then exit with code 0. Set a timeout, for example 10 seconds, after which you force exit. In Kubernetes or behind a load balancer, also fail the readiness check first so traffic stops reaching the instance.
34
Your API becomes unresponsive whenever a user uploads an image for resizing. What is happening and how do you fix it?
Resizing is CPU-bound work running on the main thread, so it blocks the event loop and every other request waits. Fix it by moving the work off the main thread: use a worker_threads pool, a native library like sharp that works in the libuv pool, or better, push a job to a queue such as BullMQ with Redis and process it in a separate worker service, then notify the client.
35
What are replica sets and sharding in MongoDB, and how do you choose a shard key?
A replica set is a primary plus secondaries holding copies of data, giving automatic failover and optional read scaling. Sharding splits a collection across multiple shards for horizontal scaling of data size and write throughput. A good shard key has high cardinality, evenly distributed writes and matches common queries so they target one shard. Monotonic keys like createdAt create hot spots unless hashed.
36
How does the useEffect dependency array work and why is cleanup important?
useEffect runs after render. With no array it runs after every render, with an empty array only after mount, and with dependencies whenever any of them change by Object.is comparison. The function you return is the cleanup, which runs before the next effect and on unmount. Use it to remove listeners, clear intervals, abort requests and close sockets, otherwise you get leaks and duplicate subscriptions.
Which companies hire MERN Stack professionals in Lucknow?
Companies with large offices in Lucknow include HCLTech. Use their company pages below to practise employer-specific sets.
Are MERN Stack interviews in Lucknow different from other cities?
The questions depend more on the company than the city. Lucknow's mix of employers decides the style: Many Lucknow candidates target Noida and Gurgaon roles or remote jobs, so interviews follow the NCR pattern
How do I find MERN Stack jobs in Lucknow?
Shortlist companies with Lucknow offices, keep your CV focused on MERN Stack projects, apply on company career pages and job portals with the Lucknow filter, and practise the questions on this page before each interview.