📋 Quick Navigation - All Questions
🟢 Basic React Questions (1-6)
🟡 Intermediate React Questions (7-11)
🔴 Advanced React Questions (12-16)
🟣 Theory-Based Questions (17-20)
Basic React Questions
React is a JavaScript library used to build user interfaces (UI) for web applications. It helps create reusable UI components, manage the state of an application, and efficiently update the UI when data changes. React is used because it makes building fast, interactive, and scalable web apps easier.
A component is a reusable piece of code that defines a part of the UI, like a button, form, or header. There are two types:
Functional Components: Simple functions that return JSX.
Class Components: Classes that extend React.Component and have a render method.
Example of a functional component:
function Welcome() { return <h1>Hello, World!</h1>; }
Props (short for properties) are used to pass data from a parent component to a child component. Props are read-only, meaning a child component cannot change the props it receives.
Example:
function Greeting(props) { return <h1>Hello, {props.name}!</h1>; } <Greeting name="Alice" />
State is an object that holds data that a component can use and change over time. When the state changes, React re-renders the component to reflect the new data. State is managed within a component (using useState in functional components or this.state in class components).
Example:
import { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Add</button> </div> ); }
JSX stands for JavaScript XML. It is a syntax extension for JavaScript that looks like HTML but allows you to write UI elements in JavaScript. JSX makes React code easier to read and write.
Example:
const element = <h1>Hello, World!</h1>;
Props | State |
---|---|
Data passed from parent to child | Data managed within a component |
Read-only (cannot be changed by child) | Can be changed using setState or useState |
External data for a component | Internal data for a component |
Example: <Button label="Click" /> |
Example: const [count, setCount] = useState(0); |
Intermediate React Questions
The Virtual DOM is a lightweight copy of the real DOM (Document Object Model). React uses it to improve performance. When state or props change, React updates the Virtual DOM first, compares it with the previous version (using a process called reconciliation), and then updates only the changed parts in the real DOM.
Lifecycle methods are special methods in class components that run at specific stages of a component's life (mounting, updating, unmounting). Examples:
componentDidMount: Runs after the component is added to the DOM (e.g., fetch data).
componentDidUpdate: Runs after the component updates (e.g., when props/state change).
componentWillUnmount: Runs before the component is removed (e.g., clean up timers).
Example:
class MyComponent extends React.Component { componentDidMount() { console.log("Component is mounted!"); } render() { return <div>Hello</div>; } }
Hooks are functions that let you use state and other React features in functional components. They were introduced in React 16.8 to avoid class components. Common hooks:
useState: Manages state in functional components.
useEffect: Handles side effects (like fetching data or setting timers).
Example:
import { useState, useEffect } from 'react'; function Example() { const [data, setData] = useState(null); useEffect(() => { fetchData().then(result => setData(result)); }, []); return <div>{data}</div>; }
useEffect is a hook used to handle side effects in functional components, such as fetching data, updating the DOM, or setting up subscriptions. It runs after the component renders.
• The first argument is a function with the side effect.
• The second argument (dependency array) controls when the effect runs.
Example:
useEffect(() => { console.log("Effect ran!"); }, [count]); // Runs when `count` changes
The key prop is a special attribute used when rendering lists in React. It helps React identify which items in a list have changed, added, or removed, making updates more efficient.
Example:
const items = ['Apple', 'Banana', 'Orange']; return ( <ul> {items.map((item, index) => ( <li key={index}>{item}</li> ))} </ul> );
Advanced React Questions
Controlled Components: Form inputs whose value is controlled by React state.
Example:
function Form() { const [value, setValue] = useState(''); return <input value={value} onChange={(e) => setValue(e.target.value)} />; }
Uncontrolled Components: Form inputs that store their own value in the DOM (accessed via refs).
Example:
function Form() { const inputRef = useRef(); return <input ref={inputRef} />; }
The Context API allows you to share data (like themes or user info) across components without passing props manually through every level of the component tree.
Example:
const ThemeContext = React.createContext('light'); function App() { return ( <ThemeContext.Provider value="dark"> <Child /> </ThemeContext.Provider> ); } function Child() { const theme = useContext(ThemeContext); return <p>Theme: {theme}</p>; }
A higher-order component (HOC) is a function that takes a component and returns a new component with additional functionality. HOCs are used for code reuse, like adding authentication or data fetching.
Example:
function withLogger(WrappedComponent) { return function(props) { console.log('Rendering', WrappedComponent.name); return <WrappedComponent {...props} />; }; } const EnhancedComponent = withLogger(MyComponent);
React Router is a library for handling navigation and routing in React apps. It allows you to create single-page applications with multiple views. Key components:
BrowserRouter: Wraps the app to enable routing.
Route: Maps a URL path to a component.
Link: Creates navigation links.
Example:
import { BrowserRouter, Route, Link } from 'react-router-dom'; function App() { return ( <BrowserRouter> <Link to="/home">Home</Link> <Route path="/home" component={Home} /> </BrowserRouter> ); }
To improve performance:
Use React.memo: Prevents unnecessary re-renders of functional components.
const MyComponent = React.memo(() => <div>Hello</div>);
Avoid unnecessary state updates: Use shouldComponentUpdate or React.memo.
Use lazy loading: Load components only when needed with React.lazy and Suspense.
const LazyComponent = React.lazy(() => import('./Component'));
Optimize re-renders: Avoid inline functions and objects in JSX.
Use production build: Run npm run build for optimized code.
Practical/Theory-Based Questions
useState: Manages simple state in functional components. Best for independent values (e.g., a counter).
const [count, setCount] = useState(0);
useReducer: Manages complex state logic with a reducer function. Best for state with multiple sub-values or dependencies.
function reducer(state, action) { switch (action.type) { case 'increment': return { count: state.count + 1 }; default: return state; } } const [state, dispatch] = useReducer(reducer, { count: 0 });
React uses synthetic events, a cross-browser wrapper around native DOM events. Event handlers are attached to elements in JSX and are named in camelCase (e.g., onClick instead of onclick).
Example:
function Button() { const handleClick = () => alert('Clicked!'); return <button onClick={handleClick}>Click me</button>; }
Prop drilling is when you pass props through multiple levels of components to reach a deeply nested component. It can make code messy.
To avoid it:
• Use Context API to share data globally.
• Use state management libraries like Redux or Zustand.
• Restructure components to reduce nesting.
Server-side rendering means rendering React components on the server and sending the HTML to the client. This improves performance and SEO. Frameworks like Next.js make SSR easier.
Example (in Next.js):
export async function getServerSideProps() { const data = await fetchData(); return { props: { data } }; } function Page({ data }) { return <div>{data}</div>; }
Common Coding Questions
Use useEffect to fetch data when the component mounts.
Example:
import { useState, useEffect } from 'react'; function DataFetcher() { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => setData(data)); }, []); return <div>{data ? data.name : 'Loading...'}</div>; }
Use controlled components to manage form input values with state.
import React, { useState } from "react"; function SimpleForm() { const [formData, setFormData] = useState({ name: "", email: "", profilePic: null, }); // Handle input change const handleChange = (e) => { const { name, value, files } = e.target; if (name === "profilePic") { setFormData({ ...formData, profilePic: files[0] }); } else { setFormData({ ...formData, [name]: value }); } }; // Handle form submit const handleSubmit = (e) => { e.preventDefault(); console.log("Form Data:", formData); }; return ( <form onSubmit={handleSubmit} className="space-y-4 p-4"> <div> <label>Name:</label> <input type="text" name="name" value={formData.name} onChange={handleChange} className="border p-2 rounded w-full" required /> </div> <div> <label>Email:</label> <input type="email" name="email" value={formData.email} onChange={handleChange} className="border p-2 rounded w-full" required /> </div> <div> <label>Profile Picture:</label> <input type="file" name="profilePic" onChange={handleChange} accept="image/*" className="border p-2 rounded w-full" /> </div> <button type="submit" className="bg-blue-500 text-white px-4 py-2 rounded" > Submit </button> </form> ); } export default SimpleForm;
Use conditional operators (&&, ||, ternary) or if statements to render components based on conditions.
Example:
function Conditional() { const [isLoggedIn, setIsLoggedIn] = useState(false); return ( <div> {isLoggedIn ? <Welcome /> : <Login />} <button onClick={() => setIsLoggedIn(!isLoggedIn)}> Toggle Login </button> </div> ); }
Use Error Boundaries to catch errors in components and display a fallback UI.
Example:
class ErrorBoundary extends React.Component { state = { hasError: false }; static getDerivedStateFromError(error) { return { hasError: true }; } render() { if (this.state.hasError) { return <h1>Something went wrong!</h1>; } return this.props.children; } } function App() { return ( <ErrorBoundary> <MyComponent /> </ErrorBoundary> ); }
Redux is a state management library. Steps to use it:
1. Install redux and react-redux.
2. Create a store with a reducer.
3. Use Provider to make the store available.
4. Use useSelector and useDispatch to access and update state.
Example:
import { createStore } from 'redux'; import { Provider, useSelector, useDispatch } from 'react-redux'; const reducer = (state = { count: 0 }, action) => { switch (action.type) { case 'INCREMENT': return { count: state.count + 1 }; default: return state; } }; const store = createStore(reducer); function App() { return ( <Provider store={store}> <Counter /> </Provider> ); } function Counter() { const count = useSelector(state => state.count); const dispatch = useDispatch(); return ( <div> <p>Count: {count}</p> <button onClick={() => dispatch({ type: 'INCREMENT' })}>Add</button> </div> ); }
🎯 Additional Tips for React Interviews
- Understand the basics: Be clear on components, props, state, and JSX.
- Practice hooks: useState, useEffect, useContext, and useReducer are commonly asked.
- Know performance optimization: Be ready to explain React.memo, lazy loading, and avoiding unnecessary renders.
- Be prepared to code: Practice building small apps (e.g., a todo list or form) to demonstrate your skills.
- Learn modern React: Focus on functional components and hooks, as class components are less common now.
- Understand the ecosystem: Familiarize yourself with popular libraries like React Router, Redux, and testing tools.
- Practice whiteboard coding: Be ready to write React code on paper or a whiteboard without an IDE.
🚀 Quick Study Tips
- Use the question index above to jump directly to topics you want to review
- Practice coding examples in a code editor to build muscle memory
- Explain concepts out loud as if teaching someone else
- Build a small project using multiple concepts from this guide
- Review error messages and debugging techniques in React DevTools