Advertisement
Google Ad Slot: content-top
React Interview Questions
1. What is the Virtual DOM?
The Virtual DOM is a lightweight JavaScript representation of the actual DOM. React uses it to track changes in the UI. When a component's state changes, React creates a new virtual DOM tree and compares it with the previous one (diffing). Then it updates only the parts of the real DOM that changed, improving performance.
Why use the Virtual DOM?
✅ Direct manipulation of the real DOM is slow
✅ React uses the VDOM to minimize DOM updates
✅ This makes apps faster and more efficient
How React Uses the Virtual DOM:
- You build a UI using React components.
- React renders a virtual DOM tree from your components.
- When state/props change, React:
- Creates a new virtual DOM.
- Compares it to the previous one (diffing).
- Finds what changed.
- Efficiently updates only the changed parts in the real DOM.
What Happens Internally?
1.First render → VDOM:
<h2>Counter: 0</h2>
2.You click the button → count becomes 1
New VDOM:
<h2>Counter: 1</h2>
3.React compares old and new VDOM, finds the text difference in <h2>, and updates only that part in the real DOM.
✅ Fast
✅ Efficient
✅ Smooth UI
2. What are controlled vs uncontrolled components?
Controlled components have their state managed by React (via useState or this.state). Their values are updated through props or state. Uncontrolled components rely on the DOM to manage state, often using useRef to access values.
Feature |
Controlled Component |
Uncontrolled Component |
|---|---|---|
Data stored in |
React state |
DOM (via ref) |
React controls input? |
✅ Yes |
❌ No |
Easier to validate? |
✅ Yes |
❌ Harder |
Use case |
Most React forms |
Simple or legacy forms |
Controlled Component
In a controlled component, the input's value is tied to React state. You control the value using useState.
Uncontrolled Component
In an uncontrolled component, the input's value is stored in the DOM, and you access it via a ref.
3. What is the difference between useEffect, useLayoutEffect, and useInsertionEffect?
Hook |
When it runs |
Use case |
|---|---|---|
useEffect |
After render (painted on screen) |
Side effects like API calls |
useLayoutEffect |
After DOM mutations but before paint |
Measure DOM size/layout before painting |
useInsertionEffect |
Before DOM mutations (CSS only) |
Injecting styles (like Emotion, styled-components) |
useEffect – Normal Side Effects
- API calls
- Subscriptions
- Analytics
- Logging
useLayoutEffect – Synchronous Side Effects
- Reading layout (
getBoundingClientRect) - Preventing flicker
- Scroll positioning
useInsertionEffect – CSS Injection (⚠️ Rarely used)
- Injecting styles dynamically (used by styled-components/emotion)
- Avoiding flickering when injecting CSS