React Interview Guide
Comprehensive guide covering React hooks, lifecycle methods, state management, and performance optimization techniques.
Introduction
React is a JavaScript library for building user interfaces with reusable components. This guide covers the essential concepts, hooks, and patterns you need to master for React interviews.
We'll explore functional components, hooks, state management, performance optimization, and real-world interview questions.
Functional Components and Hooks
Modern React uses functional components with hooks instead of class components. Hooks allow you to use state and other React features without writing a class.
import React, { useState, useEffect } from 'react';
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
export default Counter;Key hooks to know: useState, useEffect, useContext, useReducer, useCallback, useMemo, and custom hooks.
State Management
Understanding how to manage state is crucial for building scalable React applications.
- Local component state with useState
- Lifting state up to parent components
- Context API for global state
- Redux or Zustand for complex state management
- React Query for server state
Performance Optimization
React provides several tools to optimize performance:
// React.memo for preventing unnecessary re-renders
const MyComponent = React.memo(function MyComponent(props) {
return <div>{props.value}</div>;
});
// useCallback to memoize callback functions
const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);
// useMemo to memoize expensive computations
const memoizedValue = useMemo(() => {
return expensiveFunction(a, b);
}, [a, b]);Common Interview Questions
1. What is the difference between controlled and uncontrolled components?
Controlled components have their state managed by React, while uncontrolled components manage their own state in the DOM.
2. Explain the dependency array in useEffect
The dependency array determines when the effect runs. If it's empty, it runs once on mount. If it contains values, it runs when those values change.