1. What is React and what are its key features?
Answer: React is a JavaScript library for building user interfaces, created by Facebook. Key features include:
Component-Based Architecture: UI built from reusable components
Virtual DOM: Efficient updating by comparing virtual representations
Unidirectional Data Flow: Predictable state management
JSX: JavaScript syntax extension for writing HTML-like structures
Declarative UI: Describe what UI should look like for different states
2. What's the difference between Real DOM and Virtual DOM?
Answer:
| Real DOM | Virtual DOM |
|---|---|
| Updates slowly | Updates faster |
| Direct HTML manipulation | Manipulates in memory |
| Creates new DOM on update | Updates only changed nodes |
| DOM manipulation expensive | DOM manipulation lightweight |
| Can update HTML directly | Can't update HTML directly |
3. What are Components in React?
Answer: Components are independent, reusable pieces of UI. They accept props as input and return React elements describing what should appear on screen. Two types:
Functional Components: JavaScript functions (preferred with hooks)
Class Components: ES6 classes with lifecycle methods
4. What is JSX?
Answer: JSX (JavaScript XML) is a syntax extension that allows writing HTML-like code in JavaScript. It gets transpiled to React.createElement() calls by Babel.
// JSX const element = <h1>Hello, React!</h1>; // Transpiled to: const element = React.createElement('h1', null, 'Hello, React!');
5. What are Props in React?
Answer: Props (properties) are read-only inputs passed from parent to child components. They allow data flow between components and make components reusable.
// Parent Component <UserProfile name="John" age={25} /> // Child Component function UserProfile(props) { return <div>{props.name} is {props.age} years old</div>; }
6. What is State in React?
Answer: State is a built-in object that contains data that may change over a component's lifetime. Unlike props, state is managed within the component and can be updated using setState() (class) or state hooks (function).
7. Differentiate between State and Props.
Answer:
| State | Props |
|---|---|
| Mutable within component | Immutable (read-only) |
| Managed within component | Passed from parent component |
| Can be initialized and changed | Can only be passed and received |
| Local to component | Can be passed to any component |
Accessed via this.state (class) or useState | Accessed via this.props or function params |
8. What are Controlled Components?
Answer: Controlled components are form elements whose value is controlled by React state. The component's state serves as the "single source of truth."
function ControlledInput() { const [value, setValue] = useState(''); return ( <input type="text" value={value} onChange={(e) => setValue(e.target.value)} /> ); }
9. What are Uncontrolled Components?
Answer: Uncontrolled components store their own state internally using refs to access DOM values directly, similar to traditional HTML form elements.
function UncontrolledInput() { const inputRef = useRef(null); const handleSubmit = () => { console.log(inputRef.current.value); }; return <input type="text" ref={inputRef} />; }
10. What are React Hooks?
Answer: Hooks are functions that let you use state and other React features in functional components. Introduced in React 16.8, they allow functional components to have stateful logic without classes.
11. Explain the useState Hook.
Answer: useState is a hook that lets you add React state to functional components. It returns an array with two elements: the current state value and a function to update it.
const [count, setCount] = useState(0); // count = current state (0) // setCount = function to update state
12. Explain the useEffect Hook.
Answer: useEffect lets you perform side effects in functional components. It combines the functionality of componentDidMount, componentDidUpdate, and componentWillUnmount.
useEffect(() => { // Side effect code here console.log('Component mounted or updated'); return () => { // Cleanup code (like componentWillUnmount) }; }, [dependency]); // Dependency array
13. What are Keys in React and why are they important?
Answer: Keys are special string attributes that help React identify which items have changed, been added, or removed. They should be stable, predictable, and unique among siblings.
{items.map(item => ( <li key={item.id}>{item.name}</li> ))}
14. What is Reconciliation in React?
Answer: Reconciliation is React's algorithm for diffing one tree with another to determine which parts need to be changed. It's the process through which React updates the DOM by comparing the Virtual DOM with the previous version.
15. What are Fragments?
Answer: Fragments let you group a list of children without adding extra nodes to the DOM.
// Without Fragment return ( <div> <ChildA /> <ChildB /> </div> ); // With Fragment return ( <> <ChildA /> <ChildB /> </> );
Component Lifecycle (8 Questions)
16. Explain React Component Lifecycle Methods.
Answer: Lifecycle methods are special methods in class components that get called at different stages of a component's life:
Mounting:
constructor()- Initial setupstatic getDerivedStateFromProps()- Rarely usedrender()- Required, returns JSXcomponentDidMount()- After mounting to DOM
Updating:
static getDerivedStateFromProps()shouldComponentUpdate()- Performance optimizationrender()getSnapshotBeforeUpdate()- Capture DOM infocomponentDidUpdate()- After updates
Unmounting:
componentWillUnmount()- Cleanup
17. What is componentDidMount()?
Answer: Called after a component is mounted to the DOM. Ideal for:
API calls
Setting up subscriptions
DOM manipulations
Adding event listeners
18. What is componentDidUpdate()?
Answer: Called after the component updates (except initial render). Receives previous props and state as parameters.
componentDidUpdate(prevProps, prevState) { if (this.props.userID !== prevProps.userID) { this.fetchData(this.props.userID); } }
19. What is componentWillUnmount()?
Answer: Called right before a component is destroyed. Used for cleanup:
Canceling network requests
Removing event listeners
Clearing timers/intervals
20. What is shouldComponentUpdate()?
Answer: A performance optimization method that determines if a component should re-render. By default returns true. Can compare current vs next props/state.
shouldComponentUpdate(nextProps, nextState) { return this.props.color !== nextProps.color; }
21. How do you perform API calls in React?
Answer: API calls are typically made in componentDidMount() (class) or useEffect() (function).
// Using useEffect useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => setData(data)); }, []); // Empty array = run once on mount
22. What are Error Boundaries?
Answer: React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of crashing.
class ErrorBoundary extends React.Component { state = { hasError: false }; static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { console.log(error, errorInfo); } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } }
23. How do you optimize React performance?
Answer:
Use
React.memo()for functional componentsImplement
shouldComponentUpdate()for class componentsUse
useMemo()anduseCallback()hooksCode splitting with
React.lazy()andSuspenseVirtualize long lists with
react-windoworreact-virtualizedAvoid inline function definitions in render
Use keys properly in lists
Hooks Deep Dive (10 Questions)
24. What is the Rules of Hooks?
Answer:
Only Call Hooks at the Top Level - Don't call inside loops, conditions, or nested functions
Only Call Hooks from React Functions - Call from React functional components or custom hooks
25. Explain the useContext Hook.
Answer: useContext accepts a context object and returns the current context value for that context.
const ThemeContext = React.createContext('light'); function ThemedButton() { const theme = useContext(ThemeContext); return <button className={theme}>Click me</button>; }
26. Explain the useReducer Hook.
Answer: useReducer is an alternative to useState for managing complex state logic. It's similar to Redux pattern.
const [state, dispatch] = useReducer(reducer, initialState); function reducer(state, action) { switch (action.type) { case 'increment': return { count: state.count + 1 }; default: return state; } }
27. Explain the useCallback Hook.
Answer: useCallback returns a memoized callback function that only changes if one of its dependencies changes.
const memoizedCallback = useCallback( () => { doSomething(a, b); }, [a, b], // Dependencies );
28. Explain the useMemo Hook.
Answer: useMemo returns a memoized value that only recomputes when dependencies change.
const expensiveValue = useMemo(() => { return computeExpensiveValue(a, b); }, [a, b]); // Recomputes only when a or b changes
29. What is useRef Hook?
Answer: useRef returns a mutable ref object whose .current property is initialized to the passed argument. It persists for the full lifetime of the component.
const inputRef = useRef(null); // Access DOM element inputRef.current.focus();
30. Create a Custom Hook example.
Answer: Custom hooks are JavaScript functions whose name starts with "use" and can call other hooks.
function useLocalStorage(key, initialValue) { const [value, setValue] = useState(() => { const stored = localStorage.getItem(key); return stored ? JSON.parse(stored) : initialValue; }); useEffect(() => { localStorage.setItem(key, JSON.stringify(value)); }, [key, value]); return [value, setValue]; }
31. What is the purpose of dependency array in useEffect?
Answer: The dependency array controls when the effect runs:
[]- Runs once after initial render (mount)[dep1, dep2]- Runs when any dependency changesNo array - Runs after every render
32. How to handle multiple states with useState?
Answer: Either use multiple useState calls or use an object state:
// Multiple state variables const [name, setName] = useState(''); const [age, setAge] = useState(0); const [email, setEmail] = useState(''); // Single object state const [user, setUser] = useState({ name: '', age: 0, email: '' });
33. What is the difference between useMemo and useCallback?
Answer:
useMemoreturns a memoized value (result of a function)useCallbackreturns a memoized function
State Management (7 Questions)
34. What is Lifting State Up?
Answer: Moving shared state to the closest common ancestor of components that need it. This ensures a single source of truth.
function Parent() { const [count, setCount] = useState(0); return ( <> <ChildA count={count} /> <ChildB setCount={setCount} /> </> ); }
35. What is Prop Drilling and how to avoid it?
Answer: Prop drilling is passing props through multiple intermediate components. Avoid using:
Context API - For global state
State management libraries - Redux, MobX
Component composition - Render props, children
36. What is Context API?
Answer: Context provides a way to pass data through the component tree without passing props down manually at every level.
// Create Context const UserContext = React.createContext(); // Provide Context <UserContext.Provider value={currentUser}> <App /> </UserContext.Provider> // Consume Context const user = useContext(UserContext);
37. Compare Redux vs Context API.
Answer:
| Feature | Redux | Context API |
|---|---|---|
| Purpose | Full state management | Prop drilling solution |
| Complexity | High | Low |
| Boilerplate | More | Less |
| DevTools | Excellent | Basic |
| Middleware | Yes | No |
| Performance | Optimized | Can cause re-renders |
38. What are Higher-Order Components (HOC)?
Answer: HOCs are functions that take a component and return a new component with enhanced functionality.
function withLoading(Component) { return function EnhancedComponent({ isLoading, ...props }) { if (isLoading) return <div>Loading...</div>; return <Component {...props} />; }; }
39. What are Render Props?
Answer: A technique for sharing code between components using a prop whose value is a function.
<DataProvider render={data => (
<h1>Hello {data.target}</h1>
)} />40. What is the difference between Element and Component?
Answer:
Element: Plain object describing what you want to see on screen
Component: Function or class that returns elements
// Element const element = <h1>Hello</h1>; // Component const Component = () => <h1>Hello</h1>;
Advanced Concepts (10 Questions)
41. What is React Router?
Answer: React Router is the standard routing library for React. It enables navigation between views of different components.
import { BrowserRouter, Route, Switch } from 'react-router-dom'; <BrowserRouter> <Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> </Switch> </BrowserRouter>
42. What is Code Splitting in React?
Answer: Code splitting divides your bundle into smaller chunks that can be loaded on demand, improving initial load time.
const OtherComponent = React.lazy(() => import('./OtherComponent')); <Suspense fallback={<div>Loading...</div>}> <OtherComponent /> </Suspense>
43. What are React Portals?
Answer: Portals provide a way to render children into a DOM node that exists outside the parent component's DOM hierarchy.
ReactDOM.createPortal( child, document.getElementById('modal-root') );
44. What is React.StrictMode?
Answer: StrictMode is a tool for highlighting potential problems in an application. It activates additional checks and warnings for its descendants.
<React.StrictMode> <App /> </React.StrictMode>
45. How to handle events in React?
Answer: React events are named using camelCase and pass functions as event handlers.
<button onClick={handleClick}> Click me </button> function handleClick(event) { event.preventDefault(); console.log('Button clicked'); }
46. What is Synthetic Event in React?
Answer: React's cross-browser wrapper around the browser's native event. It normalizes events to work identically across all browsers.
47. What are Refs and when to use them?
Answer: Refs provide a way to access DOM nodes or React elements. Use cases:
Managing focus, text selection, or media playback
Triggering imperative animations
Integrating with third-party DOM libraries
48. What is Server-Side Rendering (SSR) in React?
Answer: SSR is rendering React components on the server and sending HTML to the browser. Benefits include:
Better SEO
Faster initial page load
Better performance on low-end devices
49. What are React.PureComponent?
Answer: PureComponent implements shouldComponentUpdate() with a shallow prop and state comparison, preventing unnecessary re-renders.
class MyComponent extends React.PureComponent { // Only re-renders if props/state shallowly change }
50. What is React.memo()?
Answer: React.memo() is a higher-order component for functional components similar to PureComponent.
const MyComponent = React.memo(function MyComponent(props) { // Only re-renders if props change });
Practical & Scenario-Based (5 Questions)
51. How would you handle forms in React?
Answer: Two approaches:
// Controlled Component Approach function Form() { const [formData, setFormData] = useState({ username: '', email: '' }); const handleChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value }); }; const handleSubmit = (e) => { e.preventDefault(); console.log(formData); }; return ( <form onSubmit={handleSubmit}> <input name="username" value={formData.username} onChange={handleChange} /> <input name="email" value={formData.email} onChange={handleChange} /> <button type="submit">Submit</button> </form> ); }
52. How to prevent component from re-rendering?
Answer:
Use
React.memo()for functional componentsExtend
PureComponentfor class componentsImplement
shouldComponentUpdate()Use
useMemo()anduseCallback()hooksOptimize context usage to avoid unnecessary consumers
53. How to fetch data when component mounts?
Answer: Using useEffect with empty dependency array:
function DataFetcher() { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { async function fetchData() { try { const response = await fetch('https://api.example.com/data'); const result = await response.json(); setData(result); } catch (err) { setError(err); } finally { setLoading(false); } } fetchData(); }, []); // Empty array = run once on mount if (loading) return <div>Loading...</div>; if (error) return <div>Error: {error.message}</div>; return <div>{JSON.stringify(data)}</div>; }
54. How to optimize large lists in React?
Answer:
Virtualization - Render only visible items
Windowing - Using libraries like
react-windowPagination - Load data in chunks
Lazy loading - Load items as user scrolls
Use keys properly - Stable, unique keys
55. How to share logic between components?
Answer:
Custom Hooks - Most modern approach
Higher-Order Components (HOC) - Wrap components
Render Props - Share code via props
Context API - Share global state/logic
Component Composition - Pass components as props
Tips for Interview Success
Understand Fundamentals Deeply: Don't just memorize, understand why
Practice Coding Examples: Be ready for live coding exercises
Explain Your Thought Process: Interviewers want to see how you think
Know When to Use What: Understand trade-offs between different approaches
Stay Updated: Know React 18+ features (Concurrent Features, Automatic Batching, etc.)
Ask Clarifying Questions: Shows problem-solving mindset
Be Honest: It's okay to say "I don't know, but here's how I'd find out"