Q1: What is React and what are its key features?
Answer: React is a declarative, efficient, and flexible JavaScript library for building user interfaces. Key features include:
Component-Based Architecture: Build encapsulated components that manage their own state
Virtual DOM: Improves performance by minimizing direct DOM manipulation
JSX: JavaScript XML syntax extension for writing HTML-like code in JavaScript
Unidirectional Data Flow: Data flows from parent to child components
React Native: Framework for building native mobile applications
Q2: What is JSX? How does it differ from HTML?
Answer: JSX is a syntax extension for JavaScript that allows writing HTML-like code in JavaScript files.
// JSX Example const element = <h1 className="greeting">Hello, World!</h1>; // Compiled to: const element = React.createElement( 'h1', {className: 'greeting'}, 'Hello, World!' );
Differences from HTML:
Uses
classNameinstead ofclassUses
htmlForinstead offorInline styles are written as objects:
style={{color: 'red'}}Must have a single root element
Self-closing tags must end with
/:<img />
Q3: Explain the Virtual DOM and its benefits
Answer: The Virtual DOM is a lightweight copy of the actual DOM maintained by React.
How it works:
When state changes, React creates a new Virtual DOM tree
Compares new Virtual DOM with previous one (diffing algorithm)
Calculates the minimal set of DOM operations needed
Updates the real DOM efficiently
Benefits:
Performance optimization by minimizing direct DOM manipulation
Efficient updates through batched operations
Cross-platform compatibility (React Native uses Virtual DOM for native views)
Q4: What are props in React?
Answer: Props (properties) are read-only inputs to components. They are passed from parent to child components and are immutable.
// Parent Component function App() { return <Greeting name="John" age={25} />; } // Child Component function Greeting(props) { return <h1>Hello, {props.name}! Age: {props.age}</h1>; }
Q5: What is the difference between Element and Component?
Answer:
Element: Plain object describing what should appear on screen
const element = <h1>Hello</h1>;
Component: Function or class that returns React elements
function Welcome() { return <h1>Hello</h1>; }
Q6: Explain React 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 ( <React.Fragment> <ChildA /> <ChildB /> </React.Fragment> ); // Short syntax return ( <> <ChildA /> <ChildB /> </> );
Q7: What are keys in React and why are they important?
Answer: Keys help React identify which items have changed, are added, or are removed in lists.
const todoItems = todos.map((todo) => <li key={todo.id}>{todo.text}</li> );
Importance:
Provide stable identity for elements
Improve performance by helping React identify minimal changes
Prevent bugs when list order changes
Q8: What are controlled vs uncontrolled components?
Answer:
Controlled Component: Form data is handled by React state
function ControlledForm() { const [value, setValue] = useState(''); return <input value={value} onChange={(e) => setValue(e.target.value)} />; }
Uncontrolled Component: Form data is handled by the DOM itself
function UncontrolledForm() { const inputRef = useRef(); return <input ref={inputRef} defaultValue="Hello" />; }
Q9: Explain React's synthetic events
Answer: React uses synthetic events which are cross-browser wrappers around native browser events.
Features:
Consistent across browsers
Event pooling for performance
Uses event delegation
Q10: What is prop drilling and how can it be avoided?
Answer: Prop drilling is passing props through multiple levels of components.
Solutions:
Context API
State management libraries (Redux, Zustand)
Component composition
Custom hooks
Q11: Explain React's reconciliation process
Answer: Reconciliation is the process through which React updates the DOM by comparing the new Virtual DOM with the previous one.
Q12: What are Pure Components?
Answer: Pure Components automatically implement shouldComponentUpdate() with shallow prop and state comparison.
class PureComp extends React.PureComponent { render() { return <div>{this.props.value}</div>; } }
Q13: What is the significance of React.StrictMode?
Answer: StrictMode is a tool for highlighting potential problems in development:
Identifies unsafe lifecycle methods
Warns about legacy string ref API usage
Detects unexpected side effects
Warns about deprecated findDOMNode usage
Q14: Can React work without JSX?
Answer: Yes, React can work without JSX using React.createElement():
// With JSX const element = <h1 className="greeting">Hello</h1>; // Without JSX const element = React.createElement( 'h1', {className: 'greeting'}, 'Hello' );
Q15: What are portals in React?
Answer: Portals provide a way to render children into a DOM node that exists outside the parent component's DOM hierarchy.
ReactDOM.createPortal( child, container );
<a name="components-props"></a>2. Components & Props (10 Questions)
Q16: What are the different ways to create components?
Answer:
Function Components (Recommended)
function Welcome(props) { return <h1>Hello, {props.name}</h1>; }
Class Components
class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } }
Arrow Function Components
const Welcome = (props) => { return <h1>Hello, {props.name}</h1>; };
Q17: What are Higher-Order Components (HOC)?
Answer: HOC is a function that takes a component and returns a new component with enhanced functionality.
function withLogger(WrappedComponent) { return function(props) { console.log('Props:', props); return <WrappedComponent {...props} />; }; } const EnhancedComponent = withLogger(MyComponent);
Q18: What are render props?
Answer: Render props is a technique for sharing code between components using a prop whose value is a function.
<DataProvider render={data => (
<h1>Hello {data.target}</h1>
)}/>Q19: How do you conditionally render components?
Answer:
// 1. Using ternary operator {isLoggedIn ? <LogoutButton /> : <LoginButton />} // 2. Using && operator {isLoading && <Spinner />} // 3. Using if statements function Greeting(props) { if (props.isLoggedIn) { return <UserGreeting />; } return <GuestGreeting />; } // 4. Using variables let button; if (isLoggedIn) { button = <LogoutButton />; } else { button = <LoginButton />; }
Q20: What are default props?
Answer: Default props allow you to set default values for props.
function Welcome(props) { return <h1>Hello, {props.name}</h1>; } Welcome.defaultProps = { name: 'Guest' }; // Or with destructuring function Welcome({name = 'Guest'}) { return <h1>Hello, {name}</h1>; }
Q21: How do you handle events in React?
Answer:
function Button() { const handleClick = (e) => { e.preventDefault(); console.log('Clicked!'); }; return <button onClick={handleClick}>Click me</button>; }
Q22: What is the children prop?
Answer: children is a special prop that contains content between opening and closing tags of a component.
function Card({children}) { return <div className="card">{children}</div>; } // Usage <Card> <h1>Title</h1> <p>Content</p> </Card>
Q23: How do you validate props?
Answer: Using PropTypes or TypeScript.
import PropTypes from 'prop-types'; function User({name, age}) { return <div>{name}, {age}</div>; } User.propTypes = { name: PropTypes.string.isRequired, age: PropTypes.number };
Q24: What is component composition?
Answer: Building complex UIs by combining smaller, reusable components.
Q25: How do you create reusable components?
Answer:
Keep components small and focused
Use props for customization
Implement proper prop validation
Create compound components for complex functionality
<a name="state-lifecycle"></a>3. State & Lifecycle (12 Questions)
Q26: What is state in React?
Answer: State is a JavaScript object that stores component-specific data that changes over time.
function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }
Q27: What is the difference between state and props?
Answer:
| State | Props |
|---|---|
| Mutable | Immutable |
| Managed within component | Passed from parent |
| Can be updated using setState | Read-only |
| Component-specific | Shared between components |
Q28: Explain React component lifecycle methods
Answer:
Class Components Lifecycle:
Mounting:
constructor()static getDerivedStateFromProps()render()componentDidMount()
Updating:
static getDerivedStateFromProps()shouldComponentUpdate()render()getSnapshotBeforeUpdate()componentDidUpdate()
Unmounting:
componentWillUnmount()
Q29: What is componentDidMount() used for?
Answer: Called after component is rendered to DOM. Used for:
API calls
Setting up subscriptions
Initializing third-party libraries
DOM manipulations
Q30: What is componentDidUpdate() used for?
Answer: Called after component updates. Used for:
Performing side effects based on prop/state changes
Network requests when props change
DOM updates
Q31: What is componentWillUnmount() used for?
Answer: Called before component is destroyed. Used for:
Cleaning up subscriptions
Cancelling network requests
Removing event listeners
Q32: How do you update state correctly?
Answer:
// For simple updates setCount(count + 1); // For state updates based on previous state setCount(prevCount => prevCount + 1); // For multiple state updates setUser(prevUser => ({ ...prevUser, age: 25 }));
Q33: What is lifting state up?
Answer: Moving state to the closest common ancestor of components that need it.
Q34: How do you handle asynchronous state updates?
Answer: Using the functional form of setState or useEffect for async operations.
Q35: What are derived states?
Answer: State that can be computed from props or other state.
Q36: Explain error boundaries
Answer: Components that catch JavaScript errors anywhere in their child component tree.
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.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; } }
Q37: How to prevent unnecessary re-renders?
Answer:
Use React.memo for functional components
Use PureComponent for class components
Implement shouldComponentUpdate
Use useMemo and useCallback hooks
Split components to isolate state changes
<a name="hooks"></a>4. Hooks (15 Questions)
Q38: What are React Hooks?
Answer: Hooks are functions that let you use state and other React features in functional components.
Rules of Hooks:
Only call hooks at the top level
Only call hooks from React functions
Q39: Explain useState hook
Answer: Allows functional components to have state.
const [state, setState] = useState(initialState);
Q40: Explain useEffect hook
Answer: Handles side effects in functional components.
useEffect(() => { // Side effect code return () => { // Cleanup code }; }, [dependencies]);
Q41: Explain useContext hook
Answer: Allows consuming context in functional components.
const value = useContext(MyContext);
Q42: Explain useRef hook
Answer: Creates a mutable ref object that persists for the lifetime of the component.
const inputRef = useRef(); // Accessing inputRef.current.focus();
Q43: Explain useMemo hook
Answer: Memoizes expensive calculations.
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
Q44: Explain useCallback hook
Answer: Memoizes functions to prevent unnecessary re-renders.
const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b]);
Q45: Explain useReducer hook
Answer: Alternative to useState for complex state logic.
const [state, dispatch] = useReducer(reducer, initialState);
Q46: Create a custom hook example
Answer:
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]; }
Q47: What is the difference between useEffect and useLayoutEffect?
Answer: useLayoutEffect fires synchronously after DOM mutations but before painting.
Q48: How to fetch data with hooks?
Answer:
function useFetch(url) { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { fetch(url) .then(res => res.json()) .then(data => { setData(data); setLoading(false); }) .catch(err => { setError(err); setLoading(false); }); }, [url]); return { data, loading, error }; }
Q49: What is the dependency array in useEffect?
Answer: Array of values that trigger the effect when changed. Empty array [] runs effect only on mount.
Q50: How to handle multiple states with hooks?
Answer: Use multiple useState hooks or useReducer for complex state.
Q51: Explain useImperativeHandle hook
Answer: Customizes the instance value exposed to parent components when using ref.
Q52: What is the purpose of useDebugValue?
Answer: Displays a label for custom hooks in React DevTools.
<a name="routing"></a>5. Routing & Navigation (8 Questions)
Q53: What is React Router?
Answer: Most popular routing library for React applications.
Q54: How to implement basic routing?
Answer:
import { BrowserRouter, Routes, Route } from 'react-router-dom'; function App() { return ( <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/users/:id" element={<User />} /> </Routes> </BrowserRouter> ); }
Q55: What is the difference between BrowserRouter and HashRouter?
Answer:
BrowserRouter: Uses HTML5 History API (clean URLs)HashRouter: Uses URL hash (works without server configuration)
Q56: How to handle 404 pages?
Answer:
<Route path="*" element={<NotFound />} />Q57: How to navigate programmatically?
Answer:
import { useNavigate } from 'react-router-dom'; function Component() { const navigate = useNavigate(); const handleClick = () => { navigate('/home'); }; return <button onClick={handleClick}>Go Home</button>; }
Q58: How to pass data between routes?
Answer: Using URL parameters, query strings, or state:
navigate('/user', { state: { id: 1 } });
Q59: What are route guards?
Answer: Protecting routes based on authentication/authorization.
function PrivateRoute({ children }) { const auth = useAuth(); return auth ? children : <Navigate to="/login" />; }
Q60: How to handle nested routes?
Answer:
<Route path="/dashboard" element={<Dashboard />}> <Route path="profile" element={<Profile />} /> <Route path="settings" element={<Settings />} /> </Route>
<a name="performance"></a>6. Performance & Optimization (10 Questions)
Q61: How to optimize React app performance?
Answer:
Code splitting with React.lazy and Suspense
Memoization with React.memo, useMemo, useCallback
Virtualization for large lists
Optimize images and assets
Use production build
Q62: What is code splitting?
Answer: Splitting code into smaller bundles loaded on demand.
const OtherComponent = React.lazy(() => import('./OtherComponent')); function MyComponent() { return ( <Suspense fallback={<div>Loading...</div>}> <OtherComponent /> </Suspense> ); }
Q63: Explain React.memo
Answer: Higher-order component that memoizes functional components.
const MemoizedComponent = React.memo(MyComponent);
Q64: When to use useMemo vs useCallback?
Answer:
useMemo: Memoize computed valuesuseCallback: Memoize functions
Q65: What is virtualization?
Answer: Rendering only visible items in large lists (using react-window or react-virtualized).
Q66: How to identify performance bottlenecks?
Answer:
React DevTools Profiler
Chrome Performance tab
Console.time() for specific operations
Q67: What is windowing?
Answer: Another term for virtualization - rendering only visible content.
Q68: How to optimize bundle size?
Answer:
Tree shaking
Code splitting
Compressing assets
Removing unused dependencies
Using dynamic imports
Q69: What is React's concurrent features?
Answer: Set of features that help apps stay responsive.
Q70: How to implement infinite scrolling?
Answer: Using Intersection Observer API or libraries like react-infinite-scroller.
<a name="advanced"></a>7. Advanced Concepts (10 Questions)
Q71: What is Redux and why use it?
Answer: Predictable state container for JavaScript apps.
Core Concepts:
Store: Single source of truth
Actions: Plain objects describing what happened
Reducers: Pure functions that specify how state changes
Q72: What is Context API?
Answer: Built-in state management for passing data through component tree.
const ThemeContext = createContext('light'); function App() { return ( <ThemeContext.Provider value="dark"> <Toolbar /> </ThemeContext.Provider> ); }
Q73: What are React Server Components?
Answer: Components that render on the server to reduce bundle size.
Q74: Explain React's Suspense for data fetching
Answer: Lets components wait for something before rendering.
Q75: What is Next.js?
Answer: React framework with server-side rendering, static generation, and other features.
Q76: What are React Error Boundaries?
Answer: Components that catch JavaScript errors in their child tree.
Q77: How to test React components?
Answer: Using Jest and React Testing Library.
Q78: What is TypeScript with React?
Answer: Adding static typing to React for better developer experience.
Q79: What are React's concurrent features?
Answer: Features like useTransition, useDeferredValue for better user experience.
Q80: What is React Query/TanStack Query?
Answer: Library for fetching, caching, and updating server state.
<a name="scenarios"></a>8. Real-world Scenarios (10 Questions)
Q81: How would you structure a large React application?
Answer:
src/ ├── components/ │ ├── common/ │ ├── features/ │ └── layouts/ ├── hooks/ ├── utils/ ├── services/ ├── store/ (or context/) ├── pages/ └── styles/
Q82: How to handle authentication in React?
Answer: Using Context, localStorage, and protected routes.
Q83: How to implement pagination?
Answer: Using query parameters and state management.
Q84: How to handle forms with validation?
Answer: Using Formik or React Hook Form with validation libraries.
Q85: How to implement dark mode?
Answer: Using Context API and CSS variables.
Q86: How to handle file uploads?
Answer: Using FormData API and file input.
Q87: How to implement real-time features?
Answer: Using WebSockets or libraries like Socket.io.
Q88: How to integrate with REST APIs?
Answer: Using fetch or Axios with proper error handling.
Q89: How to implement search functionality?
Answer: Debounced input with API calls or client-side filtering.
Q90: How to handle multiple languages?
Answer: Using i18next or react-intl libraries.
🎯 Quick Tips for Interview Success
Practice Common Patterns: Master useState, useEffect, and component composition
Build Projects: Create at least 2-3 complete React applications
Understand the "Why": Be ready to explain why React works the way it does
Review Performance: Know common optimization techniques
Stay Updated: Follow React blog and RFCs for new features
Prepare Questions: Ask insightful questions about the company's React usage
📚 Resources for Preparation
Official Docs: react.dev
Practice: Frontend Mentor, Codewars
Blogs: React Blog, Overreacted, CSS-Tricks
Courses: React Official Tutorial, Epic React
Tools: React DevTools, ESLint, Prettier