React
React Interview Questions
Master the most common React interview questions with detailed explanations and code examples.
React interviews can feel overwhelming. But here's the secret: most companies ask the same 20-30 questions. Master these, and you'll walk into any React interview with confidence. I've conducted hundreds of React interviews at startups and big tech. The patterns are predictable. Candidates who understand the fundamentals deeply always outperform those who memorize frameworks.Core Concepts Questions
Every React interview starts with fundamentals. These questions test if you understand what React actually does, not just how to copy-paste code. Question 1: What is React and why use it? This sounds basic, but many candidates stumble here. They recite marketing speak instead of showing real understanding.// Before React - manual DOM updates
function updateUserCount(count) {
document.getElementById('count').textContent = count;
document.getElementById('badge').style.display = count > 0 ? 'block' : 'none';
// More manual updates...
}
// With React - describe what you want
function UserCount({ count }) {
return (
<div>
<span id="count">{count}</span>
{count > 0 && <span className="badge">Active</span>}
</div>
);
}
What makes this better?
The virtual DOM is React's in-memory representation of the real DOM. When state changes, React creates a new virtual DOM tree, compares it to the previous one (diffing), and updates only what changed. This prevents you from writing manual DOM manipulation code and makes updates more predictable.
// DataFlow dashboard example
function DataflowChart({ chartType, data }) { // Props - external data
const [isLoading, setIsLoading] = useState(false); // State - internal data
const [selectedPeriod, setSelectedPeriod] = useState('month');
return (
<div>
<h3>{chartType} Analytics</h3> {/* Props from parent */}
<select value={selectedPeriod} onChange={(e) => setSelectedPeriod(e.target.value)}>
<option>week</option>
<option>month</option>
</select>
{isLoading ? <div>Loading...</div> : <ChartDisplay data={data} />}
</div>
);
}
The Real Difference
Props are like function parameters - they come from outside and you can't change them. State is like local variables - owned by the component and can change over time. Props flow down from parent to child. State triggers re-renders when it changes.
Hooks Deep Dive
Hooks questions are where interviews get technical. Expect to explain not just how hooks work, but when and why to use each one. Question 4: Explain useState and its gotchas Everyone knows the basic useState syntax. But can you explain why state updates are asynchronous and how to handle that?function DataflowStats() {
const [revenue, setRevenue] = useState(0);
// Wrong - doesn't work as expected
const handleBadUpdate = () => {
setRevenue(revenue + 1000);
setRevenue(revenue + 1000); // Still uses old revenue value!
console.log(revenue); // Still old value!
};
// Right - functional updates
const handleGoodUpdate = () => {
setRevenue(prev => prev + 1000);
setRevenue(prev => prev + 1000); // Uses latest value
};
return (
<div>
<h3>Revenue: ${revenue}</h3>
<button onClick={handleGoodUpdate}>Add Revenue</button>
</div>
);
}
The Critical Difference
useEffect runs after the DOM updates are painted to screen. useLayoutEffect runs before painting. Use useLayoutEffect when you need to measure DOM elements or prevent visual flicker.
// Custom hook for DataFlow API calls
function useDataflowApi(endpoint) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
async function fetchData() {
try {
setLoading(true);
const response = await fetch(`/api/${endpoint}`);
const result = await response.json();
setData(result);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
fetchData();
}, [endpoint]);
return { data, loading, error };
}
Performance Questions
Senior React roles always include performance questions. They want to know if you can build apps that scale. Question 7: How do you optimize React performance? This is a broad question with many valid answers. Show you know multiple techniques.React.memo
Prevents re-renders when props haven't changed
useMemo
Memoizes expensive calculations
useCallback
Memoizes functions to prevent child re-renders
Code Splitting
Lazy load components with React.lazy
// DataFlow user card that might re-render unnecessarily
const UserCard = React.memo(function UserCard({ user, onEdit }) {
console.log('UserCard rendered for:', user.name);
return (
<div className="user-card">
<h4>{user.name}</h4>
<p>{user.role}</p>
<button onClick={() => onEdit(user.id)}>Edit</button>
</div>
);
});
// Parent component
function UserList() {
const [users, setUsers] = useState([]);
const [searchTerm, setSearchTerm] = useState('');
// Without useCallback, UserCard re-renders on every parent render
const handleEdit = useCallback((userId) => {
// Edit logic
}, []);
return (
<div>
{users.map(user => (
<UserCard key={user.id} user={user} onEdit={handleEdit} />
))}
</div>
);
}
Tricky Behavior Questions
These questions test edge cases and React's internal behavior. They separate candidates who really understand React from those who just use it. Question 9: Why do keys matter in lists? Everyone knows to add keys to list items. But do you know what happens when you don't?// DataFlow transaction list - demonstrates key importance
function TransactionList() {
const [transactions, setTransactions] = useState([
{ id: 1, amount: 1500, description: 'Netflix Subscription' },
{ id: 2, amount: 800, description: 'Airbnb Booking' }
]);
const addTransaction = () => {
const newTransaction = {
id: Date.now(),
amount: Math.floor(Math.random() * 1000),
description: 'New Transaction'
};
setTransactions([newTransaction, ...transactions]); // Add to beginning
};
return (
<div>
<button onClick={addTransaction}>Add Transaction</button>
{transactions.map(transaction => (
<div key={transaction.id}> {/* Proper key */}
<input defaultValue={transaction.description} />
<span>${transaction.amount}</span>
</div>
))}
</div>
);
}
Practical Coding Questions
Many interviews include live coding. These questions test if you can actually build things with React. Question 11: Build a counter with increment/decrement This seems simple but tests multiple concepts: state management, event handling, and component structure.// DataFlow KPI counter component
function KPICounter({ label, initialValue = 0 }) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(prev => prev + 1);
const decrement = () => setCount(prev => prev - 1);
const reset = () => setCount(initialValue);
return (
<div style={{ padding: '20px', border: '1px solid #ccc', borderRadius: '8px' }}>
<h3>{label}</h3>
<div style={{ fontSize: '2em', margin: '10px 0' }}>{count}</div>
<button onClick={decrement}>-</button>
<button onClick={reset} style={{ margin: '0 10px' }}>Reset</button>
<button onClick={increment}>+</button>
</div>
);
}
What just happened?
The counter uses functional state updates to ensure each operation works correctly. The reset button demonstrates accessing props inside event handlers. Try clicking the buttons to see state updates in action.
function DataflowUserForm() {
const [formData, setFormData] = useState({ name: '', email: '', role: '' });
const [errors, setErrors] = useState({});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData(prev => ({ ...prev, [name]: value }));
// Clear error when user starts typing
if (errors[name]) {
setErrors(prev => ({ ...prev, [name]: '' }));
}
};
const validate = () => {
const newErrors = {};
if (!formData.name.trim()) newErrors.name = 'Name is required';
if (!formData.email.includes('@')) newErrors.email = 'Valid email required';
if (!formData.role) newErrors.role = 'Please select a role';
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleSubmit = (e) => {
e.preventDefault();
if (validate()) {
alert('User created successfully!');
setFormData({ name: '', email: '', role: '' });
}
};
return (
<form onSubmit={handleSubmit} style={{ maxWidth: '400px' }}>
<div style={{ marginBottom: '15px' }}>
<input
name="name"
value={formData.name}
onChange={handleChange}
placeholder="Full Name"
style={{ width: '100%', padding: '8px' }}
/>
{errors.name && <div style={{ color: 'red', fontSize: '12px' }}>{errors.name}</div>}
</div>
<div style={{ marginBottom: '15px' }}>
<input
name="email"
value={formData.email}
onChange={handleChange}
placeholder="Email"
style={{ width: '100%', padding: '8px' }}
/>
{errors.email && <div style={{ color: 'red', fontSize: '12px' }}>{errors.email}</div>}
</div>
<div style={{ marginBottom: '15px' }}>
<select
name="role"
value={formData.role}
onChange={handleChange}
style={{ width: '100%', padding: '8px' }}
>
<option value="">Select Role</option>
<option value="admin">Admin</option>
<option value="user">User</option>
</select>
{errors.role && <div style={{ color: 'red', fontSize: '12px' }}>{errors.role}</div>}
</div>
<button type="submit" style={{ padding: '10px 20px', background: '#007bff', color: 'white', border: 'none', borderRadius: '4px' }}>
Create User
</button>
</form>
);
}
How to Prepare
The best way to prepare for React interviews isn't memorizing answers. It's understanding the problems React solves. Build real projects. Not todo apps - everyone builds those. Build something complex enough that you run into real React challenges. A dashboard like DataFlow forces you to handle state management, performance, forms, and data fetching. Practice explaining your code. Many great developers fail interviews because they can't articulate their thinking. Record yourself explaining React concepts out loud.Common Mistakes
Don't just memorize hook syntax. Understand when to use each hook and why. Don't focus only on happy path code - interviewers love asking about edge cases and error handling. Don't skip the fundamentals - many candidates fail on basic questions because they jumped straight to advanced topics.
Quiz
1. The DataFlow team asks you to explain how React's virtual DOM improves performance. What's the best answer?
2. You're building a DataFlow counter but setState(count + 1) called twice only increments by 1. What's the solution?
3. Your DataFlow dashboard has performance issues. A user asks when to use React.memo. What do you tell them?
Up Next: Mini Project – Todo App
Put your React skills to the test by building a complete todo application with state management, forms, and local storage.