0% found this document useful (0 votes)
25 views19 pages

React - Js & Node - Js Interview Questions For Freshers - 2025

The document provides a comprehensive list of interview questions and answers for freshers focusing on React.js and Node.js for the year 2025. It covers key concepts such as React features, hooks, class vs functional components, the Context API, Node.js event loop, middleware in Express.js, and API handling. Additionally, it includes practical examples and explanations of new features in React and Node.js versions 18, 19, 20, and 21.

Uploaded by

dwarkeshboghara
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views19 pages

React - Js & Node - Js Interview Questions For Freshers - 2025

The document provides a comprehensive list of interview questions and answers for freshers focusing on React.js and Node.js for the year 2025. It covers key concepts such as React features, hooks, class vs functional components, the Context API, Node.js event loop, middleware in Express.js, and API handling. Additionally, it includes practical examples and explanations of new features in React and Node.js versions 18, 19, 20, and 21.

Uploaded by

dwarkeshboghara
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[Link] & Node.

js Interview Questions for Freshers - 2025


[Link] Interview Questions

1. What is React and what are its key features?


Answer: React is a JavaScript library for building user interfaces, particularly web applications. Key
features include:

Virtual DOM: Creates a virtual representation of the DOM for better performance

Component-Based Architecture: UI built with reusable components

JSX: Syntax extension allowing HTML-like code in JavaScript

One-way Data Binding: Data flows in a single direction


React Hooks: Functions that let you use state and lifecycle features in functional components

Server-Side Rendering: Support for SSR with frameworks like [Link]

2. What's new in React 18 and React 19 (2024-2025)?


Answer: React 18:

Concurrent Features: Automatic batching, transitions, and suspense


New Root API: createRoot() instead of [Link]()
Strict Mode Changes: Double-invokes effects in development

New Hooks: useId , useDeferredValue , useTransition

React 19 (Latest):

React Compiler: Automatic optimization without manual memoization


Server Components: Better server-side rendering capabilities

Actions: New way to handle form submissions and mutations


Enhanced Suspense: Better streaming and error boundaries
New Hooks: use() hook for consuming promises and context

3. Explain the difference between functional and class components.


Answer:

javascript
// Functional Component (Modern Approach)
import React, { useState, useEffect } from 'react';

const FunctionalComponent = ({ name }) => {


const [count, setCount] = useState(0);

useEffect(() => {
[Link] = `Count: ${count}`;
}, [count]);

return (
<div>
<h1>Hello, {name}</h1>
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
</div>
);
};

// Class Component (Legacy)


class ClassComponent extends [Link] {
constructor(props) {
super(props);
[Link] = { count: 0 };
}

componentDidMount() {
[Link] = `Count: ${[Link]}`;
}

componentDidUpdate() {
[Link] = `Count: ${[Link]}`;
}

render() {
return (
<div>
<h1>Hello, {[Link]}</h1>
<button onClick={() => [Link]({ count: [Link] + 1 })}>
Count: {[Link]}
</button>
</div>
);
}
}

4. What are React Hooks and explain the most commonly used ones?
Answer: React Hooks are functions that let you use state and lifecycle features in functional components.

Common Hooks:

useState: Manages component state

useEffect: Handles side effects (API calls, subscriptions)

useContext: Consumes React context

useReducer: Alternative to useState for complex state logic

useMemo: Memoizes expensive calculations


useCallback: Memoizes functions to prevent unnecessary re-renders

useRef: Creates mutable references that persist across renders

javascript
import React, { useState, useEffect, useMemo, useCallback } from 'react';

const HooksExample = ({ items }) => {


const [count, setCount] = useState(0);
const [filter, setFilter] = useState('');

// useEffect for side effects


useEffect(() => {
[Link] = `Count: ${count}`;
}, [count]);

// useMemo for expensive calculations


const filteredItems = useMemo(() => {
return [Link](item => [Link](filter));
}, [items, filter]);

// useCallback for function memoization


const handleIncrement = useCallback(() => {
setCount(prev => prev + 1);
}, []);

return (
<div>
<button onClick={handleIncrement}>Count: {count}</button>
<input
value={filter}
onChange={(e) => setFilter([Link])}
placeholder="Filter items"
/>
<ul>
{[Link](item => <li key={item}>{item}</li>)}
</ul>
</div>
);
};

5. Explain the concept of lifting state up in React.


Answer: Lifting state up means moving state from child components to their closest common ancestor
when multiple components need to share the same data.

javascript
// Parent Component
const ParentComponent = () => {
const [sharedData, setSharedData] = useState('');

return (
<div>
<ChildA data={sharedData} onDataChange={setSharedData} />
<ChildB data={sharedData} />
</div>
);
};

// Child A can modify the data


const ChildA = ({ data, onDataChange }) => (
<input value={data} onChange={(e) => onDataChange([Link])} />
);

// Child B displays the data


const ChildB = ({ data }) => <p>Data: {data}</p>;

6. What is the Context API and when would you use it?
Answer: Context API provides a way to pass data through the component tree without having to pass
props down manually at every level.

javascript
import React, { createContext, useContext, useState } from 'react';

// Create Context
const ThemeContext = createContext();

// Provider Component
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light');

const toggleTheme = () => {


setTheme(prev => prev === 'light' ? 'dark' : 'light');
};

return (
<[Link] value={{ theme, toggleTheme }}>
{children}
</[Link]>
);
};

// Consumer Component
const ThemedButton = () => {
const { theme, toggleTheme } = useContext(ThemeContext);

return (
<button
style={{
background: theme === 'light' ? '#fff' : '#333',
color: theme === 'light' ? '#333' : '#fff'
}}
onClick={toggleTheme}
>
Toggle Theme
</button>
);
};

[Link] Interview Questions

7. What is [Link] and what makes it different from traditional web servers?
Answer: [Link] is a JavaScript runtime built on Chrome's V8 JavaScript engine that allows you to run
JavaScript on the server-side.

Key Differences:
Event-Driven & Non-Blocking I/O: Single-threaded event loop handles multiple requests

JavaScript Everywhere: Same language for both frontend and backend

NPM Ecosystem: Largest package repository


High Performance: Excellent for I/O intensive applications

Real-time Applications: Perfect for chat apps, gaming, collaboration tools

8. Explain the Event Loop in [Link].


Answer: The Event Loop is what allows [Link] to perform non-blocking I/O operations despite being
single-threaded.

Event Loop Phases:

1. Timer Phase: Executes callbacks scheduled by setTimeout() and setInterval()

2. Pending Callbacks: Executes I/O callbacks deferred to the next loop iteration

3. Idle, Prepare: Internal use only

4. Poll Phase: Fetches new I/O events; executes I/O related callbacks

5. Check Phase: Executes setImmediate() callbacks

6. Close Callbacks: Executes close callbacks

javascript

[Link]('Start');

setTimeout(() => [Link]('Timer 1'), 0);


setImmediate(() => [Link]('Immediate 1'));

[Link](() => [Link]('Next Tick 1'));

setTimeout(() => [Link]('Timer 2'), 0);


[Link](() => [Link]('Next Tick 2'));

[Link]('End');

// Output:
// Start
// End
// Next Tick 1
// Next Tick 2
// Timer 1
// Timer 2
// Immediate 1
9. What's new in [Link] 20 and 21 (2024-2025)?

Answer: [Link] 20 LTS (Latest LTS):

Permission Model: New security feature to restrict file system access

Built-in Test Runner: Native testing without external libraries


Web Streams API: Better compatibility with web standards

V8 11.3: Performance improvements and new JavaScript features


Single Executable Applications: Bundle [Link] apps into single executables

[Link] 21 (Current):

Stable Fetch API: No longer experimental

Built-in WebSocket Support: Native WebSocket implementation

Enhanced ESM Support: Better ES modules integration

Improved Performance: Faster startup times and memory usage

10. Explain middleware in [Link] with examples.


Answer: Middleware functions are functions that execute during the request-response cycle. They have
access to request, response, and next function.

javascript
const express = require('express');
const app = express();

// Built-in middleware
[Link]([Link]()); // Parse JSON bodies
[Link]([Link]('public')); // Serve static files

// Custom middleware
const logger = (req, res, next) => {
[Link](`${[Link]} ${[Link]} - ${new Date().toISOString()}`);
next(); // Pass control to next middleware
};

const authenticate = (req, res, next) => {


const token = [Link];
if (!token) {
return [Link](401).json({ error: 'No token provided' });
}
// Verify token logic here
[Link] = { id: 1, name: 'John' }; // Mock user
next();
};

// Apply middleware
[Link](logger);

// Route-specific middleware
[Link]('/protected', authenticate, (req, res) => {
[Link]({ message: 'Protected route', user: [Link] });
});

// Error handling middleware (must be last)


[Link]((err, req, res, next) => {
[Link]([Link]);
[Link](500).json({ error: 'Something broke!' });
});

11. How do you handle asynchronous operations in [Link]?


Answer:

javascript
// 1. Callbacks (Old way - can lead to callback hell)
const fs = require('fs');

[Link]('[Link]', 'utf8', (err, data) => {


if (err) {
[Link](err);
return;
}
[Link](data);
});

// 2. Promises
const util = require('util');
const readFile = [Link]([Link]);

readFile('[Link]', 'utf8')
.then(data => [Link](data))
.catch(err => [Link](err));

// 3. Async/Await (Modern approach)


const readFileAsync = async () => {
try {
const data = await readFile('[Link]', 'utf8');
[Link](data);
} catch (err) {
[Link](err);
}
};

// 4. Modern [Link] with [Link]


const fsPromises = require('fs').promises;

const modernReadFile = async () => {


try {
const data = await [Link]('[Link]', 'utf8');
[Link](data);
} catch (err) {
[Link](err);
}
};

12. Explain different types of modules in [Link].


Answer: 1. Core Modules (Built-in):

javascript
const fs = require('fs');
const http = require('http');
const path = require('path');

2. Local Modules:

javascript

// [Link]
[Link] = (a, b) => a + b;
[Link] = (a, b) => a - b;

// Or using [Link]
[Link] = {
add: (a, b) => a + b,
subtract: (a, b) => a - b
};

// Using the module


const math = require('./math');
[Link]([Link](5, 3));

3. ES Modules (Modern):

javascript

// [Link] or [Link] (with "type": "module" in [Link])


export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;

// Or default export
export default {
add: (a, b) => a + b,
subtract: (a, b) => a - b
};

// Importing
import { add, subtract } from './[Link]';
import math from './[Link]'; // default import

4. Third-party Modules:

javascript
const express = require('express');
const axios = require('axios');
const _ = require('lodash');

Combined React + [Link] Questions

13. How would you structure a full-stack application with React and [Link]?
Answer:

project-root/
├── client/ # React frontend
│ ├── public/
│ ├── src/
│ │ ├── components/
│ │ ├── hooks/
│ │ ├── contexts/
│ │ ├── services/ # API calls
│ │ └── [Link]
│ ├── [Link]
│ └── .env
├── server/ # [Link] backend
│ ├── controllers/
│ ├── models/
│ ├── routes/
│ ├── middleware/
│ ├── config/
│ ├── utils/
│ ├── [Link]
│ ├── [Link]
│ ├── [Link]
│ └── .env
├── shared/ # Shared utilities/types
└── [Link]

14. How do you handle API calls in React with error handling?
Answer:

javascript
// Custom hook for API calls
import { useState, useEffect } from 'react';

const useApi = (url) => {


const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
const fetchData = async () => {
try {
setLoading(true);
const response = await fetch(url);

if (![Link]) {
throw new Error(`HTTP error! status: ${[Link]}`);
}

const result = await [Link]();


setData(result);
} catch (err) {
setError([Link]);
} finally {
setLoading(false);
}
};

fetchData();
}, [url]);

return { data, loading, error };


};

// Usage in component
const UserList = () => {
const { data: users, loading, error } = useApi('/api/users');

if (loading) return <div>Loading...</div>;


if (error) return <div>Error: {error}</div>;

return (
<ul>
{users?.map(user => (
<li key={[Link]}>{[Link]}</li>
))}
</ul>
);
};

15. Create a simple REST API endpoint with validation.


Answer:

javascript
const express = require('express');
const { body, validationResult } = require('express-validator');
const app = express();

[Link]([Link]());

// In-memory storage (use database in real app)


let users = [
{ id: 1, name: 'John Doe', email: 'john@[Link]' }
];

// Validation middleware
const validateUser = [
body('name').isLength({ min: 2 }).withMessage('Name must be at least 2 characters'),
body('email').isEmail().withMessage('Must be a valid email'),
];

// GET all users


[Link]('/api/users', (req, res) => {
[Link](users);
});

// GET user by ID
[Link]('/api/users/:id', (req, res) => {
const user = [Link](u => [Link] === parseInt([Link]));
if (!user) {
return [Link](404).json({ error: 'User not found' });
}
[Link](user);
});

// POST create user


[Link]('/api/users', validateUser, (req, res) => {
const errors = validationResult(req);
if (![Link]()) {
return [Link](400).json({ errors: [Link]() });
}

const { name, email } = [Link];


const newUser = {
id: [Link] + 1,
name,
email
};

[Link](newUser);
[Link](201).json(newUser);
});

// PUT update user


[Link]('/api/users/:id', validateUser, (req, res) => {
const errors = validationResult(req);
if (![Link]()) {
return [Link](400).json({ errors: [Link]() });
}

const userIndex = [Link](u => [Link] === parseInt([Link]));


if (userIndex === -1) {
return [Link](404).json({ error: 'User not found' });
}

users[userIndex] = { ...users[userIndex], ...[Link] };


[Link](users[userIndex]);
});

// DELETE user
[Link]('/api/users/:id', (req, res) => {
const userIndex = [Link](u => [Link] === parseInt([Link]));
if (userIndex === -1) {
return [Link](404).json({ error: 'User not found' });
}

[Link](userIndex, 1);
[Link](204).send();
});

const PORT = [Link] || 3001;


[Link](PORT, () => {
[Link](`Server running on port ${PORT}`);
});

2025 Bonus Questions

16. What are Server Components in React 19?


Answer: Server Components run on the server and can directly access databases, file systems, or other
server-only data sources.

javascript
// [Link] (runs on server)
import { db } from './db';

const UserList = async () => {


const users = await [Link](); // Direct database access

return (
<div>
<h2>Users</h2>
{[Link](user => (
<UserCard key={[Link]} user={user} />
))}
</div>
);
};

// [Link] (runs on client)


'use client';
import { useState } from 'react';

const UserCard = ({ user }) => {


const [isExpanded, setIsExpanded] = useState(false);

return (
<div onClick={() => setIsExpanded(!isExpanded)}>
<h3>{[Link]}</h3>
{isExpanded && <p>{[Link]}</p>}
</div>
);
};

17. How would you implement real-time features using WebSocket in [Link]?
Answer:

javascript
// [Link]
const express = require('express');
const WebSocket = require('ws');
const http = require('http');

const app = express();


const server = [Link](app);
const wss = new [Link]({ server });

// Store connected clients


const clients = new Set();

[Link]('connection', (ws) => {


[Link](ws);
[Link]('Client connected');

[Link]('message', (message) => {


const data = [Link](message);

// Broadcast to all connected clients


[Link](client => {
if (client !== ws && [Link] === [Link]) {
[Link]([Link]({
type: 'message',
data: data,
timestamp: new Date().toISOString()
}));
}
});
});

[Link]('close', () => {
[Link](ws);
[Link]('Client disconnected');
});
});

[Link](3000, () => {
[Link]('Server running on port 3000');
});

Tips for Interview Success


1. Practice Coding: Be ready to write code on a whiteboard or shared screen
2. Know the Basics: Understand JavaScript fundamentals (closures, promises, async/await)
3. Stay Updated: Follow React and [Link] release notes
4. Build Projects: Have 2-3 projects ready to discuss

5. Ask Questions: Show curiosity about the company's tech stack


6. Explain Your Thinking: Walk through your problem-solving process

7. Know Common Patterns: State management, error handling, authentication


8. Performance: Understand optimization techniques (memoization, lazy loading)

Common Follow-up Topics


Testing (Jest, React Testing Library)

State Management (Redux, Zustand, Context API)


Database Integration (MongoDB, PostgreSQL)

Authentication & Authorization


Deployment (Docker, AWS, Vercel)
TypeScript basics

Version Control (Git)

You might also like