React.js interview questions covering hooks, state management, performance, virtual DOM, and modern React patterns.
8 Questions Detailed Answers
1What is the Virtual DOM? How does it work?
Easy
View Answer
The Virtual DOM is a lightweight JavaScript representation of the actual DOM. When state changes: (1) React creates a new Virtual DOM tree, (2) Diffs it with the previous one (reconciliation), (3) Calculates minimal changes needed, (4) Batch-updates the real DOM. This makes updates efficient — O(n) instead of re-rendering everything.
2Explain useState and useEffect hooks.
Easy
View Answer
`useState` manages component state: `const [count, setCount] = useState(0)`. `useEffect` handles side effects (fetching data, subscriptions): `useEffect(() => { fetchData(); return () => cleanup(); }, [dependency])`. The dependency array controls when the effect re-runs. Empty array = mount only.
3What is the difference between useMemo and useCallback?
Medium
View Answer
`useMemo` memoizes a computed value: `const total = useMemo(() => items.reduce(...), [items])`. `useCallback` memoizes a function reference: `const handleClick = useCallback(() => {...}, [deps])`. Use useMemo for expensive calculations, useCallback to prevent unnecessary child re-renders.
4Explain React context vs Redux.
Medium
View Answer
Context: built-in, for low-frequency updates (theme, auth, locale). Re-renders all consumers on change. Redux: external library, for complex state with many updates. Has middleware, devtools, predictable state updates. Rule of thumb: use Context for simple global state, Redux for complex app-wide state with actions.
5What are React Server Components?
Hard
View Answer
RSCs run on the server, sending only HTML to the client. Benefits: zero JS bundle size, direct database access, better performance. They can't use hooks, event handlers, or browser APIs. In Next.js, all components are server components by default — add "use client" for interactivity.
6How do you optimize React performance?
Medium
View Answer
Key techniques: (1) React.memo for preventing unnecessary re-renders, (2) useMemo/useCallback for expensive computations, (3) Code splitting with lazy/Suspense, (4) Virtualization for long lists (react-window), (5) Key prop optimization, (6) Avoiding inline object/function creation in JSX.
7What is the useRef hook used for?
Easy
View Answer
`useRef` creates a mutable reference that persists across renders without causing re-renders. Two uses: (1) DOM access: `const inputRef = useRef(); inputRef.current.focus()`, (2) Storing mutable values: `const prevValue = useRef(value)` — like instance variables in class components.
8Explain error boundaries in React.
Medium
View Answer
Error boundaries catch JavaScript errors in child component trees, log them, and display a fallback UI instead of crashing. Implemented as class components with `static getDerivedStateFromError()` and `componentDidCatch()`. They don't catch errors in event handlers, async code, or SSR.