Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Interview questions › React & Node.js

React & Node.js interview questions

1. What is React?

Easy

A JavaScript library (by Meta) for building user interfaces from reusable components. It updates the page efficiently using a virtual DOM and a declarative style: you describe what the UI should look like for a given state.

2. What is JSX?

Easy

A syntax extension that lets you write HTML-like markup inside JavaScript: <h1>Hello {name}</h1>. A compiler (Babel / esbuild) turns it into React.createElement (or jsx()) calls. Use className instead of class.

3. What is the virtual DOM?

Medium

A lightweight copy of the real DOM kept in memory. On a state change React builds a new virtual tree, diffs it with the old one (reconciliation) and applies only the changes to the real DOM, which is faster than re-rendering everything.

4. Props vs state?

Easy

Props are inputs passed from a parent; the component cannot change them. State is data owned by the component that can change over time (useState); changing it re-renders the component.

5. Functional vs class components?

Easy

Class components extend React.Component and use this.state and lifecycle methods. Functional components are plain functions that use hooks (useState, useEffect). Modern React code uses functional components.

6. What are hooks? Name the common ones.

Easy

Functions that let functional components use React features: useState (state), useEffect (side effects), useContext (context), useRef (refs / mutable values), useMemo and useCallback (memoisation), useReducer (complex state).

7. What are the rules of hooks?

Medium

Call hooks only at the top level of a component or custom hook — never inside loops, conditions or nested functions — and only from React functions. React relies on the call order to match state between renders.

8. How does useEffect work?

Medium

useEffect(fn, deps) runs fn after render. With [] it runs once after mount; with [a, b] when a or b change; with no array after every render. Return a function to clean up (unsubscribe, clear timers).

useEffect(() => {
  const id = setInterval(tick, 1000);
  return () => clearInterval(id);
}, []);

9. Why do lists need a `key`?

Medium

Keys tell React which item is which between renders, so it can reorder, add and remove items correctly and keep their state. Use a stable unique id — not the array index when items can be reordered or deleted.

10. Controlled vs uncontrolled components?

Easy

In a controlled input React state holds the value (value={name} onChange={e => setName(e.target.value)}). In an uncontrolled input the DOM keeps the value and you read it with a ref. Controlled inputs make validation easier.

11. What is lifting state up?

Easy

When two components need the same data, move the state to their closest common parent and pass it down as props (and pass setter functions down so children can update it).

12. What is prop drilling and how do you avoid it?

Medium

Passing props through many layers of components that don't use them. Avoid it with Context (createContext + useContext), composition (passing components as children) or a state library like Redux / Zustand.

13. What is the Context API?

Medium

A way to share values (theme, logged-in user, language) with a whole subtree without passing props at every level. Create it with createContext, provide it with <Ctx.Provider value={...}>, read it with useContext(Ctx).

14. useMemo vs useCallback?

Hard

useMemo(() => compute(a), [a]) caches a computed value. useCallback(fn, [deps]) caches a function so its identity stays the same — useful when passing callbacks to memoised children. Both only help when re-calculation is actually expensive.

15. What is React.memo?

Medium

A wrapper that skips re-rendering a component when its props are shallowly equal to the previous props. Combine it with useCallback / useMemo so the props really stay equal.

16. What is useRef used for?

Easy

To keep a mutable value that survives renders without causing a re-render (ref.current), and to access DOM elements directly, e.g. to focus an input: inputRef.current.focus().

17. How do you fetch data in React?

Easy

Inside useEffect with fetch or axios, storing data, loading and error in state; or with a library like TanStack Query / SWR that handles caching, retries and refetching.

useEffect(() => {
  fetch("/api/items").then(r => r.json()).then(setItems);
}, []);

18. What is React Router?

Easy

The standard routing library for single-page React apps. <Routes> with <Route path="/users/:id" element={<User />} /> maps URLs to components; <Link> and useNavigate change pages without reloading; useParams reads URL parameters.

19. What are higher-order components and custom hooks?

Medium

A HOC is a function that takes a component and returns a new one with extra behaviour (withAuth(Page)). A custom hook (useFetch, useAuth) shares stateful logic between components and is the modern, simpler choice.

20. How do you improve the performance of a React app?

Hard

Code-split with React.lazy + Suspense, memoise expensive parts (React.memo, useMemo), virtualise long lists, avoid unnecessary state and re-renders, optimise images, and measure with the React DevTools profiler.

21. What is reconciliation?

Hard

React's process of comparing the new element tree with the previous one to work out the minimum DOM changes. Elements of different types are replaced; same types are updated; key identifies list items.

22. What are fragments?

Easy

<>...</> (or <React.Fragment>) groups several elements without adding an extra <div> to the DOM. Use <React.Fragment key={id}> when you need a key in a list.

23. What is the difference between a SPA and a server-rendered app?

Medium

A SPA loads one HTML page and renders everything in the browser with JavaScript — fast navigation but slower first load and weaker SEO by default. Server-side rendering (Next.js) sends ready HTML from the server — faster first paint and better SEO.

24. What are error boundaries?

Medium

Components that catch JavaScript errors while rendering their children and show a fallback UI instead of a blank page. They are class components with componentDidCatch / getDerivedStateFromError (or a library like react-error-boundary).

25. Redux: what are store, actions and reducers?

Medium

The store holds the whole app state. An action is a plain object describing what happened ({ type: "cart/add", payload }). A reducer is a pure function (state, action) => newState. Redux Toolkit is the recommended way to write Redux today.

26. What is Node.js?

Easy

A JavaScript runtime built on Chrome's V8 engine that runs JavaScript outside the browser — for servers, CLIs and tools. It uses a single-threaded, non-blocking, event-driven model that handles many concurrent connections efficiently.

27. How is Node.js single-threaded but still handles many requests?

Medium

JavaScript runs on one thread, but slow I/O (files, network, DB) is handed to the operating system or the libuv thread pool. When the I/O finishes, its callback is queued and the event loop runs it, so the main thread never sits waiting.

28. What is the event loop?

Hard

The loop that keeps Node.js running: it takes completed callbacks from queues and runs them on the main thread. Phases include timers, I/O callbacks, setImmediate and close callbacks; process.nextTick and promise callbacks (microtasks) run between phases.

29. process.nextTick vs setImmediate vs setTimeout?

Hard

process.nextTick runs right after the current operation, before any I/O. Promise callbacks run next. setImmediate runs in the check phase after I/O callbacks. setTimeout(fn, 0) runs in the timers phase — the order with setImmediate can vary outside I/O callbacks.

30. Callbacks vs promises vs async/await?

Easy

Callbacks pass a function to run later and nest badly ("callback hell"). Promises represent a future value with .then/.catch. async/await is syntax over promises that reads like synchronous code, with try/catch for errors.

31. What is npm and package.json?

Easy

npm is Node's package manager. package.json lists the project's name, scripts (npm run dev), dependencies and devDependencies. package-lock.json pins exact versions so installs are repeatable.

32. CommonJS vs ES modules?

Medium

CommonJS uses require() / module.exports and loads synchronously (Node's original system). ES modules use import / export, load asynchronously and are the JavaScript standard — enable them with "type": "module" or .mjs files.

33. What is Express.js?

Easy

A minimal web framework for Node.js that adds routing, middleware, request parsing and helpers on top of the http module. It is the "E" in MERN.

const app = express();
app.use(express.json());
app.get("/api/users/:id", (req, res) => res.json({ id: req.params.id }));
app.listen(5000);

34. What is middleware in Express?

Medium

A function (req, res, next) that runs during a request — to log, parse the body, check authentication, handle errors — and then calls next() to pass control on (or ends the response). Error middleware has four arguments: (err, req, res, next).

35. How do you handle errors in an Express app?

Medium

Wrap async route handlers so rejected promises reach next(err) (Express 5 does this automatically), and add one error-handling middleware at the end that logs the error and sends a clean JSON response with the right status code.

36. What is REST? Name the HTTP methods.

Easy

An architectural style where resources are identified by URLs and handled with HTTP methods: GET (read), POST (create), PUT (replace), PATCH (update part), DELETE (remove). Responses are stateless and use status codes like 200, 201, 400, 401, 404, 500.

37. What is CORS?

Medium

Cross-Origin Resource Sharing: browsers block a page from calling an API on another origin unless the API sends headers like Access-Control-Allow-Origin. In Express, the cors middleware sets them — allow only your own front-end origins.

38. How do you implement authentication with JWT?

Medium

On login, verify the password (hashed with bcrypt) and sign a JWT with the user id. The client sends it as Authorization: Bearer <token>. A middleware verifies the token on protected routes and attaches the user to req.

39. How do you store passwords securely?

Easy

Never store plain text. Hash with a slow, salted algorithm like bcrypt or argon2 (bcrypt.hash(password, 12)), and compare with bcrypt.compare on login.

40. What are environment variables and why use them?

Easy

Values set outside the code (process.env.MONGO_URI) for secrets and settings that change between development and production. Load them locally from a .env file with dotenv, and never commit secrets to Git.

41. What are streams in Node.js?

Hard

A way to process data piece by piece instead of loading it all into memory — Readable, Writable, Duplex and Transform streams. Great for big files and video: fs.createReadStream(file).pipe(res).

42. How do you scale a Node.js application?

Hard

Run several processes (the cluster module or PM2) to use all CPU cores, put them behind a load balancer, keep servers stateless (sessions in Redis), cache results, and move heavy CPU work to worker threads or background queues.

43. What are worker threads?

Hard

Real threads (worker_threads) for CPU-heavy JavaScript (image processing, large calculations) so the main event loop stays free to answer requests. They communicate by passing messages.

44. What is Mongoose?

Easy

An ODM (object data modelling) library for MongoDB in Node.js. You define schemas with types and validation, create models, and query with methods like find, findById, create and populate (join-like references).

45. SQL vs MongoDB for a MERN app?

Medium

MongoDB stores JSON-like documents with flexible schemas, which fits JavaScript naturally and is quick to start with. A SQL database is better when data is highly relational and needs complex joins and strict transactions.

46. How do you upload files in Express?

Medium

Use middleware like multer to parse multipart/form-data, check file type and size, then store the file on disk or (better) in cloud storage like S3 / Cloudinary and save only the URL in the database.

47. How do you secure an Express API?

Medium

Use helmet for security headers, rate limiting (express-rate-limit), input validation (zod / Joi), parameterised queries, CORS limited to your origins, HTTPS, hashed passwords, short-lived JWTs and no secrets in code.

48. What is the difference between PUT and PATCH?

Easy

PUT replaces the whole resource with the data sent. PATCH updates only the fields sent. PUT is idempotent by definition; PATCH usually is too, but doesn't have to be.

49. How do the front end and back end of a MERN app talk to each other?

Easy

The React app calls the Express API over HTTP (fetch / axios), sending and receiving JSON. Express reads and writes MongoDB through Mongoose. Authentication is usually a JWT sent in the Authorization header.

50. How would you deploy a MERN app?

Medium

Build the React app and host it on Vercel / Netlify; host the Express API on Render / Railway / AWS; use MongoDB Atlas for the database; set environment variables (API URL, DB URI, JWT secret) on each host and allow the front-end origin in CORS.

More topics