Wednesday, 11 March 2026

React Interview Questions Answers Set 3

 

1. Which console.log will execute first in this code?

The interviewer referred to a question similar to this:

const data = false;

if (data) {
console.log("First");
}

if (new Boolean(false)) {
console.log("Second");
}

Correct Answer

Output:

Second

Explanation

new Boolean(false) creates a Boolean object, not a primitive.

Objects in JavaScript are always truthy.

Example:

Boolean(false) // false
new Boolean(false) // object (truthy)

So the condition becomes:

if (true)

Therefore:

Second

is printed.


2. Can we apply loop over object?

Yes.

Two main ways:

1. for...in

Used to iterate object keys.

const user = {
name: "Rahul",
age: 25
}

for (let key in user) {
console.log(key, user[key])
}

Output

name Rahul
age 25

2. Object.keys()

Object.keys(user).forEach(key => {
console.log(key, user[key])
})

3. Difference between forEach and for...in

forEach

Used for arrays

const arr = [1,2,3]

arr.forEach(num => console.log(num))

Features

  • Works only on arrays

  • Cannot break or continue

  • Returns undefined


for...in

Used for objects

for (let key in obj) {
console.log(key)
}

Features

  • Iterates over object keys


4. What is Single Source of Truth in Redux?

Answer

Redux keeps all application state in one central store.

Example:

Redux Store
|
|---- User State
|---- Product State
|---- Cart State

Benefits:

  • predictable state management

  • easier debugging

  • centralized state


5. What is Reconciliation in React?

Answer

Reconciliation is the process React uses to update the DOM efficiently.

Steps:

  1. React creates Virtual DOM

  2. React compares new Virtual DOM with old one

  3. Finds the difference (diffing algorithm)

  4. Updates only changed elements in Real DOM

Example:

<h1>Hello</h1>

changes to

<h1>Hello Rahul</h1>

React updates only the text node, not the entire DOM.


6. What is Diffing Algorithm?

React compares two Virtual DOM trees using O(n) diffing algorithm.

Rules:

  1. Different element types → re-render

  2. Same element type → update attributes

  3. React uses keys for list comparison

Example:

{users.map(user => (
<li key={user.id}>{user.name}</li>
))}

Keys help React identify which items changed.


7. What is React.memo?

React.memo prevents unnecessary re-rendering of components.

Example:

const Child = React.memo(({name}) => {
console.log("render")
return <h1>{name}</h1>
})

Component re-renders only if props change.


8. When should we use Context API vs Redux?

Context API

Use when:

  • small or medium app

  • few global states

  • authentication

  • theme

  • language

Example:

AuthContext
ThemeContext

Redux

Use when:

  • large applications

  • complex state

  • many components need same data

  • advanced debugging

Example:

Ecommerce
Large dashboards
Enterprise apps

9. Why does React re-render?

React re-renders when:

State changes
Props change
Parent re-renders
Context value changes

Example:

setCount(count + 1)

Triggers re-render.


10. Why should hooks not be used inside loops or conditions?

React uses hook call order to track state.

Wrong:

if (true) {
useState()
}

This breaks hook order.

Correct:

const [count, setCount] = useState(0)

Always at top level of component.

Share:

React Interview Questions Set 2

 

1. Why do we get Uncaught ReferenceError in JavaScript?

Answer

This error occurs when we try to access a variable that is not defined or not initialized.

Example:

console.log(a)
let a = 5

Output:

Uncaught ReferenceError: Cannot access 'a' before initialization

Reason:

  • Because of Temporal Dead Zone (TDZ) with let and const.

Another example:

console.log(x)

If x is never declared → ReferenceError.


2. Does IIFE get Hoisted?

Answer

No.

IIFE (Immediately Invoked Function Expression) is not hoisted because it is a function expression.

Example:

(function(){
console.log("Hello")
})();

Function declarations are hoisted, but function expressions are not.


3. How does JavaScript Work? (Call Stack & Event Loop)

JavaScript runtime has these components:

Call Stack
Web APIs
Callback Queue
Event Loop

Step-by-step flow

  1. Code runs in Call Stack

  2. Async tasks go to Web APIs

  3. Results go to Callback Queue

  4. Event Loop pushes tasks back to Call Stack

Example:

console.log("Start")

setTimeout(()=>{
console.log("Timeout")
},0)

console.log("End")

Output:

Start
End
Timeout

Reason: setTimeout goes to Web API → Queue → Event Loop.


4. What is Object Prototyping?

JavaScript uses prototype-based inheritance.

Every object inherits properties from another object called prototype.

Example:

const person = {
greet(){
console.log("Hello")
}
}

const user = Object.create(person)

user.greet()

Output:

Hello

user inherits from person.


5. JavaScript Middleware (in Redux)

Middleware intercepts actions before they reach the reducer.

Flow:

Component

Dispatch Action

Middleware

Reducer

Store

Example middleware:

Redux Thunk
Redux Saga
Redux Logger

Example:

const fetchData = () => async(dispatch)=>{
const res = await fetch("/api")
dispatch({type:"SET_DATA",payload:res})
}

6. Redux Toolkit vs Redux

Problem in Redux

Too much boilerplate.

Files needed:

actions.js
reducers.js
constants.js
store.js

Redux Toolkit solves this

Features:

createSlice()
configureStore()
createAsyncThunk()

Example:

const counterSlice = createSlice({
name:"counter",
initialState:{value:0},
reducers:{
increment:(state)=>{
state.value++
}
}
})

Benefits:

  • Less code

  • Built-in immutability (Immer)

  • Built-in thunk support


7. How to Call Function When Count = 5 (Without If Else)

Using useEffect.

Example:

const [count,setCount] = useState(0)

useEffect(()=>{
if(count===5){
alert("Count is 5")
}
},[count])

count is dependency → effect runs when count changes.


8. What are Pure Components?

A Pure Component re-renders only when props or state change.

It performs shallow comparison.

Class component example:

class MyComponent extends React.PureComponent {
render(){
return <h1>Hello</h1>
}
}

In functional components we achieve similar behavior using:

React.memo()

Example:

export default React.memo(MyComponent)

9. What are React Portals?

React Portal allows rendering components outside the root DOM tree.

Common use cases:

Modals
Tooltips
Popups
Dropdown overlays

Example:

ReactDOM.createPortal(
<Modal />,
document.getElementById("modal-root")
)

10. What is Code Splitting?

Code splitting divides application bundle into smaller chunks.

This improves performance and load time.

Example:

const Dashboard = React.lazy(()=>import("./Dashboard"))

Combined with:

<Suspense fallback={<Loading/>}>
<Dashboard/>
</Suspense>

11. What are React Profilers?

React Profiler is used to measure performance of components.

It helps detect:

Slow renders
Unnecessary re-renders
Performance bottlenecks

Example:

<Profiler id="App" onRender={callback}>
<App/>
</Profiler>

12. What are Render Props?

Render Props is a pattern where a component receives a function as a prop to render UI.

Example:

<DataProvider render={(data)=>(
<h1>{data}</h1>
)}/>

Used for:

Reusable logic
State sharing

13. Can We Use Hooks in Variables?

Hooks must follow rules:

Only inside React functional components
Only at top level
Not inside loops or conditions

Wrong:

if(true){
useState()
}

Correct:

const [count,setCount] = useState(0)

14. Can We Focus Input Without useRef?

Yes using DOM selector (not recommended in React):

document.getElementById("input").focus()

But React best practice:

useRef()

15. Why Avoid Prop Drilling?

Prop drilling occurs when props are passed through many components.

Example:

A → B → C → D → E

Even if only E needs the data.

Solution:

Context API
Redux
Zustand
Share:

React Interview Questions Set 1


1. Introduce Yourself

Answer

I am a React.js developer with around 2+ years of experience in frontend development. I have experience working with HTML, CSS, JavaScript, and React.js. I have worked on e-commerce applications, where I implemented UI components, handled API integration, and managed application state using Redux Toolkit. I am currently looking for opportunities to grow further and work on scalable frontend applications.


2. What are Semantic HTML Tags?

Answer

Semantic tags clearly describe the meaning of the content.

Examples:

<header>
<nav>
<section>
<article>
<footer>
<main>
<aside>

Example:

<article>
<h1>Blog Title</h1>
<p>This is a blog post</p>
</article>

Benefits:

  • Better SEO

  • Better accessibility

  • Cleaner code structure


3. What are Meta Tags?

Answer

Meta tags provide metadata about the webpage. They are written inside the <head> tag.

Example:

<meta charset="UTF-8">
<meta name="description" content="Car selling website">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

Uses:

  • SEO optimization

  • Browser configuration

  • Character encoding

  • Responsive design


4. What is Flexbox and its Properties?

Answer

Flexbox is a CSS layout system used to design responsive layouts.

To use Flexbox:

.container{
display:flex;
}

Important properties:

Container properties

flex-direction
justify-content
align-items
align-content
flex-wrap

Child properties

flex-grow
flex-shrink
flex-basis
align-self

Example:

.container{
display:flex;
justify-content:center;
align-items:center;
}

5. What are CSS Positions?

Answer

CSS Position defines how an element is positioned.

Types:

static
relative
absolute
fixed
sticky

Example:

position: relative;
position: absolute;

6. Difference Between Relative and Absolute

Relative

  • Positioned relative to its normal position.

Absolute

  • Positioned relative to the nearest positioned parent.

Example

.parent{
position:relative;
}

.child{
position:absolute;
top:10px;
}

7. What is CSS Box Model?

Answer

Every HTML element is treated as a box.

Structure:

Content
Padding
Border
Margin

Diagram:

Margin
└ Border
└ Padding
└ Content

8. Difference Between let, var, const

Featurevarletconst
ScopeFunctionBlockBlock
RedeclareYesNoNo
ReassignYesYesNo
HoistingYesYesYes

Example:

var a = 10
let b = 20
const c = 30

9. What is Temporal Dead Zone?

Answer

Temporal Dead Zone is the time between variable hoisting and initialization for let and const.

Example:

console.log(a)
let a = 5

This gives:

ReferenceError

10. What are Hoisting Types?

Answer

Two types:

  1. Variable Hoisting

var a
  1. Function Hoisting

function test(){}

Example:

hello()

function hello(){
console.log("hi")
}

11. What is IIFE?

Answer

Immediately Invoked Function Expression executes immediately.

Example:

(function(){
console.log("Hello")
})();

12. Spread vs Rest Operator

Spread Operator

Used to expand elements

...

Example:

const arr1=[1,2]
const arr2=[3,4]

const arr=[...arr1,...arr2]

Rest Operator

Used to collect multiple parameters

function sum(...numbers){
console.log(numbers)
}

13. Is JavaScript Synchronous or Asynchronous?

Answer

JavaScript is single-threaded and synchronous by default.

But asynchronous behavior is achieved using:

Promises
Async/Await
Callbacks
setTimeout
fetch API

14. Types of Functions in JavaScript

  1. Normal Function

function test(){}
  1. Function Expression

const test=function(){}
  1. Arrow Function

const test=()=>{}
  1. Anonymous Function

setTimeout(function(){},1000)

15. What are Higher Order Functions?

A function that:

  • Takes another function as argument

  • Returns a function

Example:

array.map()
array.filter()
array.reduce()

16. What are Callback Functions?

A function passed as an argument to another function.

Example:

function greet(name,callback){
callback(name)
}

function sayHello(name){
console.log("Hello "+name)
}

greet("Rahul",sayHello)

17. What is this Keyword?

this refers to the current execution context.

Examples:

Function

function test(){
console.log(this)
}

→ window object (browser)

Object

const obj={
name:"Rahul",
show(){
console.log(this.name)
}
}

→ refers to object


18. Promises vs Callback vs Async/Await

Callback

function(callback)

Problem: callback hell.


Promise

new Promise((resolve,reject)=>{})

Methods:

.then()
.catch()
.finally()

Async/Await

Cleaner syntax.

async function getData(){
const data=await fetch(url)
}

19. Promise Types

Common methods:

Promise.all()
Promise.race()
Promise.allSettled()
Promise.any()

20. Deep Copy vs Shallow Copy

Shallow Copy

Copies reference.

const obj2={...obj1}

Deep Copy

Copies completely new memory.

JSON.parse(JSON.stringify(obj))

21. Event Bubbling vs Capturing

Event Bubbling

Child → Parent

Default behavior.

Event Capturing

Parent → Child

Example:

addEventListener("click",handler,true)

22. Map vs Filter vs Reduce

Map

Transforms array.

arr.map(x=>x*2)

Filter

Filters based on condition.

arr.filter(x=>x>10)

Reduce

Reduces array to single value.

arr.reduce((sum,x)=>sum+x,0)

23. What is Currying?

Breaking a function into multiple functions.

Example:

function add(a){
return function(b){
return a+b
}
}

add(2)(3)

24. Object Destructuring

Extract values from object.

Example:

const user={
name:"Rahul",
age:25
}

const {name,age}=user

25. for...of vs for...in

for...of

Used for arrays.

values

Example:

for(const item of arr){}

for...in

Used for objects.

keys

Example:

for(const key in obj){}

26. Fetch vs Axios

FeatureFetchAxios
Built-inYesNo
JSON conversionManualAutomatic
InterceptorsNoYes
Simpler APINoYes

27. Virtual DOM vs Real DOM

Real DOM

Actual browser DOM.

Slow updates.


Virtual DOM

Lightweight copy of DOM used by React.

Benefits:

  • Faster rendering

  • Efficient updates

React compares changes using Reconciliation Algorithm.


28. React Lifecycle Phases

3 phases:

Mounting
Updating
Unmounting

Example hooks:

useEffect()

29. Controlled vs Uncontrolled Components

Controlled

React controls input state.

const [value,setValue]=useState("")

Uncontrolled

DOM handles state.

useRef()

30. Props vs State

Props

  • Passed from parent

  • Read-only

State

  • Managed inside component

  • Mutable


31. Why State Instead of Variable?

Because React re-renders UI when state changes.

Variables do not trigger re-render.


32. What are Hooks?

Hooks allow using state and lifecycle features in functional components.

Examples:

useState
useEffect
useContext
useReducer
useRef
useMemo
useCallback

33. Child to Parent Communication

Using callback function.

Example:

Parent:

const handleClick=(data)=>{
console.log(data)
}

<Child sendData={handleClick}/>

Child:

props.sendData("Hello")

34. useReducer

Used for complex state management.

Example:

const [state,dispatch]=useReducer(reducer,initialState)

35. Context API

Used for global state without prop drilling.

Example:

Theme
User Auth
Language

36. Redux Main Concepts

Three pillars:

Store
Actions
Reducers

Flow:

Component → Dispatch → Action → Reducer → Store → UI

37. useSelector vs useDispatch

useSelector

Reads data from store.

const data=useSelector(state=>state.users)

useDispatch

Dispatch action.

dispatch(addUser())

38. Lazy Loading

Loads components only when needed.

Example:

const Home = React.lazy(()=>import("./Home"))

39. React Portal

Used to render component outside DOM hierarchy.

Example:

Modals
Popups
Tooltips

40. useRef

Access DOM elements.

Example:

const inputRef=useRef()

inputRef.current.focus()

41. useMemo vs useCallback

HookPurpose
useMemoMemoizes value
useCallbackMemoizes function

Example

useMemo(()=>expensiveCalculation,[deps])
useCallback(()=>{},[deps])
Share: