Core Concepts & Fundamentals (Questions 1-15)
1. What is React and why is it so popular?
Answer: React is an open-source JavaScript library developed by Facebook for building user interfaces, particularly single-page applications. Its popularity stems from:
Component-Based Architecture: Reusable UI components simplify development and maintenance
Virtual DOM: Efficient updates improve performance
Declarative Syntax: Makes code predictable and easier to debug
Rich Ecosystem: Extensive library support (React Router, Redux, etc.)
Strong Community: Backed by Facebook and millions of developers
Learn Once, Write Anywhere: Works with React Native for mobile development
2. What are the key differences between React and traditional JavaScript?
Answer:
| Aspect | Traditional JavaScript | React |
|---|---|---|
| DOM Manipulation | Direct DOM manipulation | Virtual DOM |
| Updates | Manual updates | Automatic re-renders |
| Code Structure | Imperative (how to do) | Declarative (what to show) |
| Reusability | Limited code reuse | Component-based reusability |
| State Management | Manual state tracking | Built-in state management |
3. Explain the Virtual DOM and its advantages
Answer: The Virtual DOM is a lightweight JavaScript representation of the actual DOM. When state changes:
React creates a new Virtual DOM tree
Compares it with previous version (diffing)
Calculates minimal changes needed
Updates only those parts in the actual DOM
Advantages:
Performance: Minimizes expensive DOM operations
Efficiency: Batches multiple updates
Cross-platform: Can render to different environments
Simplified: Abstracts away direct DOM manipulation
4. What are React Components?
Answer: Components are independent, reusable pieces of UI. They accept inputs (props) and return React elements describing what should appear on screen. There are two types:
// Function Component (modern approach) function Welcome(props) { return <h1>Hello, {props.name}</h1>; } // Class Component (legacy) class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } }
5. What is JSX?
Answer: JSX (JavaScript XML) is a syntax extension that allows writing HTML-like code in JavaScript:
const element = <h1 className="greeting">Hello, world!</h1>; // Gets compiled to: const element = React.createElement( 'h1', {className: 'greeting'}, 'Hello, world!' );
Key points:
Not HTML, but syntactic sugar for
React.createElement()Must have a single root element
Use
classNameinstead ofclassJavaScript expressions inside
{}Close all tags (
<br />not<br>)
6. What are Props?
Answer: Props (properties) are read-only inputs passed to components:
// Parent component function App() { return <User name="John" age={30} />; } // Child component function User(props) { return <p>{props.name} is {props.age} years old</p>; }
Characteristics:
Immutable (cannot be modified by child)
Pass data from parent to child
Can be any JavaScript type
7. What is State in React?
Answer: State represents data that changes over time within a component:
import { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}> Increment </button> </div> ); }
8. Differentiate between Props and State
Answer:
| Aspect | Props | State |
|---|---|---|
| Mutability | Immutable | Mutable |
| Ownership | Passed from parent | Managed within component |
| Purpose | Configuration | Dynamic data |
| Initialization | From parent component | Within component |
| Updates | Cause re-render | Cause re-render |
9. What are Controlled Components?
Answer: Controlled components have their form data handled by React state:
function Form() { const [value, setValue] = useState(''); const handleChange = (event) => { setValue(event.target.value); }; return ( <input type="text" value={value} onChange={handleChange} /> ); }
The React component controls what happens in the form on subsequent user input.
10. What are Uncontrolled Components?
Answer: Uncontrolled components store their own state internally using refs:
function Form() { const inputRef = useRef(null); const handleSubmit = (event) => { alert(inputRef.current.value); event.preventDefault(); }; return ( <form onSubmit={handleSubmit}> <input type="text" ref={inputRef} /> <button type="submit">Submit</button> </form> ); }
11. What are React Fragments?
Answer: Fragments let you group elements without adding extra DOM nodes:
function List() { return ( <> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </> ); }
Or using explicit syntax:
<React.Fragment key={item.id}> {/* content */} </React.Fragment>
12. What is Conditional Rendering?
Answer: Different ways to render components conditionally:
// 1. if/else function Greeting({ isLoggedIn }) { if (isLoggedIn) { return <UserGreeting />; } return <GuestGreeting />; } // 2. Ternary operator function Message({ hasError }) { return ( <div> {hasError ? <ErrorMsg /> : <SuccessMsg />} </div> ); } // 3. Logical && operator function Notification({ messages }) { return ( <div> {messages.length > 0 && <p>You have {messages.length} unread messages</p> } </div> ); }
13. What are Lists and Keys?
Answer: Keys help React identify which items have changed, been added, or removed:
function NumberList({ numbers }) { const listItems = numbers.map((number) => <li key={number.id}>{number.value}</li> ); return <ul>{listItems}</ul>; }
Key rules:
Must be unique among siblings
Should be stable identifiers
Avoid using index as key unless list is static
14. What are React Hooks?
Answer: Hooks are functions that let you use React features in function components:
import { useState, useEffect } from 'react'; function Example() { const [count, setCount] = useState(0); useEffect(() => { document.title = `Count: ${count}`; }, [count]); return <button onClick={() => setCount(count + 1)}>Click</button>; }
15. What are the Rules of Hooks?
Answer:
Only Call Hooks at the Top Level: Don't call hooks inside loops, conditions, or nested functions
Only Call Hooks from React Functions: Call them from React function components or custom hooks
Use ESLint Plugin: React provides
eslint-plugin-react-hooksto enforce these rules
Hooks & State Management (Questions 16-30)
16. Explain the useState Hook
Answer: useState is a Hook that lets you add state to function components:
function Counter() { const [count, setCount] = useState(0); const [user, setUser] = useState({ name: 'John', age: 30 }); // Functional updates for state based on previous state const increment = () => { setCount(prevCount => prevCount + 1); }; // Updating objects const updateAge = () => { setUser(prevUser => ({ ...prevUser, age: prevUser.age + 1 })); }; }
17. Explain the useEffect Hook
Answer: useEffect handles side effects in function components:
useEffect(() => { // Side effect code here console.log('Component mounted or updated'); // Cleanup function (optional) return () => { console.log('Component will unmount'); }; }, [dependency1, dependency2]); // Dependency array
Dependency array behaviors:
[]: Runs once after initial render (componentDidMount)[dep]: Runs whendepchanges (componentDidUpdate)No array: Runs after every render
18. What are Custom Hooks?
Answer: Custom Hooks let you extract component logic into reusable functions:
// Custom Hook 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]; } // Using the custom hook function Component() { const [name, setName] = useLocalStorage('name', 'John'); // ... }
19. Explain the useContext Hook
Answer: useContext provides a way to pass data through the component tree without prop drilling:
// 1. Create Context const ThemeContext = React.createContext('light'); // 2. Provide Context function App() { return ( <ThemeContext.Provider value="dark"> <Toolbar /> </ThemeContext.Provider> ); } // 3. Consume Context function Toolbar() { const theme = useContext(ThemeContext); return <div>Current theme: {theme}</div>; }
20. Explain the useReducer Hook
Answer: useReducer is an alternative to useState for complex state logic:
const initialState = { count: 0 }; function reducer(state, action) { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: throw new Error(); } } function Counter() { const [state, dispatch] = useReducer(reducer, initialState); return ( <> Count: {state.count} <button onClick={() => dispatch({ type: 'increment' })}> + </button> </> ); }
21. Explain the useRef Hook
Answer: useRef returns a mutable ref object that persists for the lifetime of the component:
function TextInput() { const inputRef = useRef(null); const focusInput = () => { inputRef.current.focus(); }; return ( <> <input ref={inputRef} type="text" /> <button onClick={focusInput}>Focus Input</button> </> ); }
22. Explain the useMemo Hook
Answer: useMemo memoizes expensive calculations:
function ExpensiveComponent({ list }) { const sortedList = useMemo(() => { console.log('Sorting...'); return list.sort((a, b) => a - b); }, [list]); // Only re-sort when list changes return <div>{sortedList.join(', ')}</div>; }
23. Explain the useCallback Hook
Answer: useCallback returns a memoized callback function:
function Parent() { const [count, setCount] = useState(0); const increment = useCallback(() => { setCount(c => c + 1); }, []); // Function identity stays the same return <Child onIncrement={increment} />; } const Child = React.memo(function Child({ onIncrement }) { console.log('Child rendered'); return <button onClick={onIncrement}>Increment</button>; });
24. What is Prop Drilling and how to avoid it?
Answer: Prop drilling is passing props through multiple intermediate components:
// Problem: Prop drilling function App() { return <A user="John" />; } function A({ user }) { return <B user={user} />; } function B({ user }) { return <C user={user} />; // C needs user, but B doesn't } // Solutions: // 1. Context API // 2. Component composition // 3. State management libraries
25. What is Lifting State Up?
Answer: Moving shared state to the closest common ancestor:
function Parent() { const [temperature, setTemperature] = useState(''); return ( <> <Celsius temp={temperature} onChange={setTemperature} /> <Fahrenheit temp={temperature} onChange={setTemperature} /> </> ); } function Celsius({ temp, onChange }) { return ( <input value={temp} onChange={e => onChange(e.target.value)} /> ); }
Performance & Optimization (Questions 26-35)
26. How to optimize React performance?
Answer:
React.memo: Memoize functional components
useMemo/useCallback: Memoize values/functions
Code Splitting: Lazy load components
Virtualization: For large lists (react-window)
Avoid Inline Functions/Objects: In render methods
Profiler API: Identify bottlenecks
27. What is React.memo?
Answer: React.memo is a higher-order component that memoizes functional components:
const MyComponent = React.memo(function MyComponent(props) { // Renders only when props change return <div>{props.value}</div>; }); // Custom comparison function const MyComponent = React.memo( function MyComponent(props) { return <div>{props.value}</div>; }, (prevProps, nextProps) => { // Return true if props are equal (don't re-render) return prevProps.value === nextProps.value; } );
28. What is Code Splitting?
Answer: Code splitting divides your bundle into smaller chunks:
import React, { Suspense, lazy } from 'react'; const LazyComponent = lazy(() => import('./LazyComponent')); function App() { return ( <Suspense fallback={<div>Loading...</div>}> <LazyComponent /> </Suspense> ); }
29. What are Error Boundaries?
Answer: Error boundaries catch JavaScript errors in child components:
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { console.error('Error:', error, errorInfo); } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } } // Usage <ErrorBoundary> <MyComponent /> </ErrorBoundary>
30. What is Reconciliation?
Answer: Reconciliation is React's diffing algorithm that determines what needs to be updated in the DOM:
Elements of different types: Tear down old tree, build new one
DOM elements of same type: Update changed attributes only
Component elements of same type: Update props, re-render
Lists: Use keys to identify items
Advanced Concepts (Questions 36-51)
31. What are Higher-Order Components (HOCs)?
Answer: HOCs are functions that take a component and return a new component:
function withLogger(WrappedComponent) { return function(props) { console.log('Rendering:', WrappedComponent.name); return <WrappedComponent {...props} />; }; } const EnhancedComponent = withLogger(MyComponent);
32. What are Render Props?
Answer: Render props is a pattern using a prop that returns a React element:
<DataProvider render={data => ( <h1>Hello {data.target}</h1> )}/> // Or using children prop <Mouse> {mouse => ( <p>Mouse position: {mouse.x}, {mouse.y}</p> )} </Mouse>
33. What are Portals?
Answer: Portals render children into a DOM node outside parent hierarchy:
import ReactDOM from 'react-dom'; function Modal({ children }) { return ReactDOM.createPortal( children, document.getElementById('modal-root') ); }
34. What is React.StrictMode?
Answer: StrictMode is a tool for highlighting potential problems:
<React.StrictMode> <App /> </React.StrictMode>
It helps with:
Identifying unsafe lifecycles
Warning about legacy string ref API
Detecting unexpected side effects
Detecting legacy context API
35. How does React handle events?
Answer: React events are synthetic events that wrap native browser events:
function Button() { const handleClick = (event) => { event.preventDefault(); console.log('Clicked!'); // Event pooling (older React): event.persist() }; return <button onClick={handleClick}>Click me</button>; }
36. What are React Server Components? (2026 Update)
Answer: Server Components run on the server and send minimal JavaScript to client:
// Server Component (can use server-only features) async function Note({ id }) { const note = await db.notes.get(id); // Direct DB access return <NoteEditor note={note} />; }
Benefits:
Zero bundle size for server components
Direct access to backend resources
Automatic code splitting
Improved performance
37. What is Concurrent Mode?
Answer: Concurrent Mode makes React apps more responsive by:
Interruptible rendering: Can pause, resume, or abandon renders
Automatic batching: Groups multiple state updates
Transitions: Distinguish urgent vs non-urgent updates
Suspense for Data Fetching: Declarative data loading
38. What is Suspense?
Answer: Suspense lets components "wait" for something before rendering:
<Suspense fallback={<Spinner />}> <ProfilePage /> </Suspense> // With data fetching const resource = fetchProfileData(); function ProfilePage() { return ( <Suspense fallback={<h1>Loading profile...</h1>}> <ProfileDetails /> <Suspense fallback={<h1>Loading posts...</h1>}> <ProfileTimeline /> </Suspense> </Suspense> ); }
39. How to handle forms in React?
Answer:
// Controlled component approach function Form() { const [formData, setFormData] = useState({ name: '', 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="name" value={formData.name} onChange={handleChange} /> <input name="email" value={formData.email} onChange={handleChange} /> <button type="submit">Submit</button> </form> ); }
40. How to test React components?
Answer:
// Using Jest and React Testing Library import { render, screen, fireEvent } from '@testing-library/react'; import Button from './Button'; test('button clicks', () => { const handleClick = jest.fn(); render(<Button onClick={handleClick}>Click me</Button>); fireEvent.click(screen.getByText('Click me')); expect(handleClick).toHaveBeenCalledTimes(1); });
41. What are React Lifecycle Methods?
Answer: For class components (mostly replaced by Hooks):
Mounting:
constructor(),static getDerivedStateFromProps(),render(),componentDidMount()Updating:
static getDerivedStateFromProps(),shouldComponentUpdate(),render(),getSnapshotBeforeUpdate(),componentDidUpdate()Unmounting:
componentWillUnmount()Error Handling:
static getDerivedStateFromError(),componentDidCatch()
42. What is the significance of keys?
Answer: Keys help React identify which items have changed:
Without keys: React re-creates entire list on changes
With keys: React reorders/moves existing items
Bad practice: Using array indices as keys (causes issues with reordering)
Best practice: Stable, unique IDs from data
43. How to make API calls in React?
Answer:
function UserList() { const [users, setUsers] = useState([]); const [loading, setLoading] = useState(false); useEffect(() => { const fetchUsers = async () => { setLoading(true); try { const response = await fetch('/api/users'); const data = await response.json(); setUsers(data); } catch (error) { console.error('Error:', error); } finally { setLoading(false); } }; fetchUsers(); }, []); if (loading) return <div>Loading...</div>; return <ul>{users.map(user => <li key={user.id}>{user.name}</li>)}</ul>; }
44. What are Pure Components?
Answer: PureComponent implements shouldComponentUpdate with shallow prop/state comparison:
class PureCounter extends React.PureComponent { render() { return <div>{this.props.count}</div>; } }
Function component equivalent:
const PureCounter = React.memo(function PureCounter({ count }) { return <div>{count}</div>; });
45. How to handle routing in React?
Answer: Using React Router v6:
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom'; function App() { return ( <BrowserRouter> <nav> <Link to="/">Home</Link> <Link to="/about">About</Link> </nav> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/users/:id" element={<User />} /> </Routes> </BrowserRouter> ); }
46. What is Redux and when to use it?
Answer: Redux is a state management library for complex applications:
// When to use Redux: // - Large-scale applications // - Complex state logic // - Shared state across many components // - Need for time-travel debugging // - Predictable state updates // Basic Redux concepts: // - Store: Single source of truth // - Actions: Plain objects describing changes // - Reducers: Pure functions that update state // - Middleware: Handle async operations
47. What are React Refs?
Answer: Refs provide access to DOM nodes or React elements:
class AutoFocusInput extends React.Component { constructor(props) { super(props); this.inputRef = React.createRef(); } componentDidMount() { this.inputRef.current.focus(); } render() { return <input ref={this.inputRef} />; } }
48. What is Context API?
Answer: Context provides a way to share values between components without prop drilling:
const UserContext = React.createContext(); function App() { const [user, setUser] = useState({ name: 'John' }); return ( <UserContext.Provider value={{ user, setUser }}> <Navbar /> <MainContent /> </UserContext.Provider> ); } function Navbar() { const { user } = useContext(UserContext); return <nav>Welcome, {user.name}</nav>; }
49. How does React handle styling?
Answer: Multiple approaches:
Inline Styles:
style={{ color: 'red', fontSize: 20 }}CSS Modules:
import styles from './Button.module.css'Styled-components: CSS-in-JS library
Tailwind CSS: Utility-first framework
SASS/SCSS: Preprocessor integration
50. What are React Server Components vs Client Components?
Answer:
| Aspect | Server Components | Client Components |
|---|---|---|
| Bundle Size | Zero bundle | Full bundle sent |
| Data Fetching | Direct DB/API access | Client-side fetching |
| Interactivity | No event handlers | Full interactivity |
| State | No useState/useReducer | Full state management |
| Effects | No useEffect | Lifecycle effects |
51. What are the latest React features in 2026?
Answer: Current trends and features:
React Server Components: Production-ready
Actions: Simplified form handling with async operations
Enhanced Hooks: New hooks for common patterns
Improved DevTools: Better debugging capabilities
Automatic optimization: Compiler improvements
WebAssembly integration: For performance-critical tasks
Conclusion & Best Practices
React Best Practices for 2026:
Use Function Components and Hooks as primary approach
Implement proper TypeScript for type safety
Follow component composition over inheritance
Keep components small and focused (Single Responsibility)
Use meaningful naming conventions
Implement proper error boundaries
Optimize performance proactively
Write comprehensive tests
Use React's built-in features before adding libraries
Stay updated with React ecosystem
Common Interview Tips:
Understand fundamentals thoroughly
Practice coding challenges with real React problems
Explain your thought process during technical interviews
Be familiar with both old and new patterns
Discuss trade-offs between different approaches
Show understanding of performance implications
Demonstrate knowledge of React ecosystem
Ask clarifying questions before solving problems
This comprehensive guide covers the essential knowledge needed for React interviews in 2026. Remember that React continues to evolve, so staying current with official documentation and community trends is crucial for success in both interviews and real-world development.