
1. What is React?
Description:
React is a JavaScript library created by Facebook for building user interfaces, especially for single-page applications (SPAs). It lets developers create reusable UI components that manage their own state and efficiently update the UI when data changes.
Why use React?
- Declarative: Makes UI code more predictable and easier to debug.
- Component-based: Build encapsulated components that manage their state.
- Virtual DOM: Improves performance by minimizing DOM updates.
2. What are the features of React?
Description:
React’s key features include:
- Virtual DOM: React creates a lightweight in-memory representation of the real DOM, which improves performance by updating only parts that change.
- JSX: Lets you write HTML-like syntax directly in JavaScript, making components easier to read and write.
- Component-Based Architecture: Breaks the UI into independent reusable pieces.
- One-way Data Binding: Data flows in one direction, making apps more predictable.
- Performance: Efficient updates and rendering with the virtual DOM.
3. What is JSX?
Description:
JSX (JavaScript XML) is a syntax extension for JavaScript that looks similar to HTML. React components use JSX to define the UI structure. Although it looks like HTML, it’s transpiled into JavaScript function calls.
Example:
const greeting = <h1>Hello, world!</h1>;
const greeting = React.createElement('h1', null, 'Hello, world!');
4. What are components?
Description:
Components are the building blocks of a React application. Each component is a self-contained piece of UI, which can be reused and nested within other components. Components can be:
- Class Components: Use ES6 classes and can manage state and lifecycle methods.
- Functional Components: Simpler functions that return JSX, often using hooks to manage state and side effects.
Example of a Functional Component:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
5. Difference between Class and Functional Components?
Description:
- Class Components:
- Use ES6
class
syntax. - Have access to lifecycle methods (
componentDidMount
, etc.). - Use
this.state
for state management.
- Use ES6
- Functional Components:
- Are simpler JavaScript functions.
- Use React hooks like
useState
anduseEffect
to manage state and lifecycle. - Tend to be easier to read and test.
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
6. What is the virtual DOM?
Description:
The Virtual DOM is an in-memory representation of the real DOM. When state or props change, React first updates the Virtual DOM, then compares it with a previous snapshot (diffing). Finally, it updates only the parts of the actual DOM that have changed, which is faster and more efficient.
7. What are props?
Description:
Props (short for properties) are inputs to React components. They are passed down from parent components to children and are immutable inside the child. Props allow components to be dynamic and reusable.
function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
// Usage:
<Greeting name="Alice" />
8. What is state?
Description:
State is a local data storage for components. Unlike props, which are read-only, state can be changed by the component itself, typically in response to user actions or API responses. When state changes, React re-renders the component.
function Counter() {
const [count, setCount] = React.useState(0);
return (
<>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</>
);
}
9. How do you update the state?
Description:
In class components, you update state using this.setState()
, which merges the new state with the existing state and triggers a re-render.
Class Example:
this.setState({ count: this.state.count + 1 });
In functional components, you use the setter function returned by useState
:
setCount(count + 1);
10. What is the difference between state and props?
Aspect | State | Props |
---|---|---|
Managed By | Component itself | Parent component |
Mutability | Mutable (can be changed) | Immutable (read-only) |
Purpose | Stores data that affects rendering | Passes data to child components |
Usage | Used for data that changes over time | Used to configure or customize children |
11. What is the lifecycle of a React component?
Description:
React components go through a lifecycle divided into three phases:
- Mounting: When the component is created and inserted into the DOM.
- Updating: When the component’s props or state change, triggering a re-render.
- Unmounting: When the component is removed from the DOM.
Each phase has specific lifecycle methods or hooks to run code at those times.
12. Name some lifecycle methods in class components.
Description:
componentDidMount()
: Called after the component is mounted — useful for fetching data.componentDidUpdate(prevProps, prevState)
: Called after updating — good for reacting to prop or state changes.componentWillUnmount()
: Called before unmounting — useful for cleanup like removing event listeners.
class Timer extends React.Component {
componentDidMount() {
this.interval = setInterval(() => console.log('tick'), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return <div>Timer running...</div>;
}
}
13. What are hooks in React?
Description:
Hooks are special functions that let you “hook into” React features from functional components. They enable state management, lifecycle methods, and other features without using class components.
Common hooks include:
useState
for state managementuseEffect
for side effectsuseContext
for context consumption
14. What does the useState
hook do?
Description:useState
allows functional components to have state. It returns a pair: the current state value and a function to update it.
const [count, setCount] = React.useState(0);
function increment() {
setCount(count + 1);
}
14. What does the useState
hook do?
Description:useState
allows functional components to have state. It returns a pair: the current state value and a function to update it.
const [count, setCount] = React.useState(0);
function increment() {
setCount(count + 1);
}
15. What does the useEffect
hook do?
Description:useEffect
lets you perform side effects in functional components, like data fetching, subscriptions, or manually changing the DOM. It runs after every render by default but can be configured to run only when specific dependencies change.
React.useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // Only re-run effect if count changes
16. What is a controlled component?
Description:
A controlled component is a form element (input, textarea, select) where React controls the input’s value via state. The component’s state is the single source of truth.
function NameInput() {
const [name, setName] = React.useState('');
return (
<input
type="text"
value={name}
onChange={e => setName(e.target.value)}
/>
);
}
17. What is an uncontrolled component?
Description:
An uncontrolled component manages its own state internally, like traditional HTML form elements. React accesses the input’s value using refs.
function NameInput() {
const inputRef = React.useRef();
function handleSubmit() {
alert(`Entered name: ${inputRef.current.value}`);
}
return (
<>
<input type="text" ref={inputRef} />
<button onClick={handleSubmit}>Submit</button>
</>
);
}
18. What is event handling in React?
Description:
React uses a synthetic event system which is a wrapper around the browser’s native events to provide consistent behavior across browsers.
Key points:
- Use camelCase for event names, e.g.,
onClick
. - Pass a function as the event handler.
<button onClick={() => alert('Clicked!')}>Click Me</button>
19. How do you bind event handlers in React?
Description:
In class components, event handler methods don’t automatically bind this
. You can bind them in the constructor or use arrow functions.
Example (binding in constructor):
class MyButton extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log(this);
}
render() {
return <button onClick={this.handleClick}>Click</button>;
}
}
Example (arrow function):
<button onClick={() => this.handleClick()}>Click</button>
20. What is conditional rendering?
Description:
Conditional rendering means rendering components or elements based on a condition (usually state or props).
Example:
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
return (
<>
{isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign up.</h1>}
</>
);
}
21. What are lists and keys in React?
Description:
Lists in React are used to render multiple components dynamically, typically by iterating over an array. Keys are special strings that help React identify which items have changed, been added, or removed to optimize rendering.
Example:
const numbers = [1, 2, 3];
const listItems = numbers.map((number) =>
<li key={number.toString()}>{number}</li>
);
function NumberList() {
return <ul>{listItems}</ul>;
}
22. Why is a key important in lists?
Description:
Keys give React a way to track each element uniquely, preventing unnecessary re-renders and improving performance. Without keys, React uses the index by default, which can cause bugs if the list order changes.
23. What is React Router?
Description:
React Router is a library that enables navigation and routing in React apps, allowing users to switch between different components or views without full page reloads.
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
function App() {
return (
<Router>
<nav>
<Link to="/">Home</Link> | <Link to="/about">About</Link>
</nav>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
</Router>
);
}
24. What is Context API?
Description:
Context API provides a way to pass data through the component tree without having to pass props down manually at every level. It’s useful for global data like themes or user info.
const ThemeContext = React.createContext('light');
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
return <ThemedButton />;
}
function ThemedButton() {
const theme = React.useContext(ThemeContext);
return <button style={{ background: theme === 'dark' ? '#333' : '#eee' }}>Button</button>;
}
25. What are refs in React?
Description:
Refs provide a way to access DOM nodes or React elements directly. They are commonly used for focusing inputs, triggering animations, or integrating with third-party libraries.
26. How do you create refs?
Description:
You can create refs using React.createRef()
in class components or useRef()
hook in functional components.
Class component example
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
focusInput = () => {
this.myRef.current.focus();
};
render() {
return <input ref={this.myRef} />;
}
}
Functional component example:
function MyComponent() {
const inputRef = React.useRef();
const focusInput = () => {
inputRef.current.focus();
};
return <input ref={inputRef} />;
}
27. What is prop drilling?
Description:
Prop drilling occurs when you pass props through many layers of components just to get data to a deeply nested component. It can lead to cluttered and hard-to-maintain code.
28. How to avoid prop drilling?
Description:
Use React Context API or state management libraries like Redux or MobX to provide data globally, avoiding the need to pass props down multiple levels.
29. What is Redux?
Description:
Redux is a predictable state container for JavaScript apps. It centralizes the app’s state and logic, making it easier to manage and debug, especially for large applications.
30. What is a Higher-Order Component (HOC)?
Description:
A Higher-Order Component is a function that takes a component and returns a new component with enhanced capabilities. HOCs are used for code reuse, such as injecting props or managing logic.
function withLogger(WrappedComponent) {
return function(props) {
console.log('Rendering with props:', props);
return <WrappedComponent {...props} />;
};
}
22. Why is a key important in lists?
Expanded Description:
Keys help React identify which items have changed, been added, or removed in a list. Without keys, React re-renders the entire list even if only one item changes. With keys, React compares key values to selectively update only the affected items — greatly improving performance and preventing bugs, especially in dynamic lists.
Why not use index as key?
Using an index (e.g., key={index}
) can cause problems if the list changes order or items are added/removed, leading to incorrect re-renders or loss of component state.
const todos = [
{ id: 1, task: 'Learn React' },
{ id: 2, task: 'Build a Project' }
];
const list = todos.map(todo => (
<li key={todo.id}>{todo.task}</li>
));
31. What are pure components?
Description:
Pure components are components that only re-render when their props or state change. In class components, React provides React.PureComponent
, which implements shouldComponentUpdate()
with a shallow comparison.
Benefit:
Improved performance by avoiding unnecessary renders.
Example:
class MyComponent extends React.PureComponent {
render() {
return <div>{this.props.name}</div>;
}
}
32. What is React.Fragment?
Description:<React.Fragment>
lets you group multiple elements without adding extra nodes to the DOM. It’s useful when rendering sibling elements without needing an unnecessary <div>
.
return (
<React.Fragment>
<h1>Title</h1>
<p>Paragraph</p>
</React.Fragment>
);
// Short syntax
<>
<h1>Title</h1>
<p>Paragraph</p>
</>
33. Difference between React and Angular?
Feature | React | Angular |
---|---|---|
Type | Library | Framework |
Language | JavaScript/JSX | TypeScript |
DOM | Virtual DOM | Real DOM |
Data Binding | One-way | Two-way |
Learning Curve | Moderate | Steeper |
Scalability | Component-based | Full-featured & scalable |
34. What is server-side rendering (SSR)?
Description:
SSR renders components to HTML on the server before sending them to the client. This improves SEO and reduces time to first paint. It’s often implemented with frameworks like Next.js.
35. What is hydration in React?
Description:
Hydration is the process of attaching React’s event listeners and state management to a server-rendered HTML page. After SSR, React “hydrates” the static HTML so it becomes fully interactive.
36. What is lazy loading in React?
Description:
Lazy loading defers loading components until they are needed, which reduces the initial load time. React provides React.lazy()
and <Suspense>
to handle this.
const LazyComponent = React.lazy(() => import('./MyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
37. How does React handle forms?
Description:
Forms can be managed using controlled or uncontrolled components. In a controlled form, React keeps form input values in the component’s state, providing more control and validation options.
const [email, setEmail] = useState('');
<form onSubmit={...}>
<input value={email} onChange={e => setEmail(e.target.value)} />
</form>
38. What is reconciliation in React?
Description:
Reconciliation is React’s diffing algorithm that compares the previous and new virtual DOMs. React calculates the minimal number of operations to update the real DOM, improving performance.
39. How do you optimize performance in React?
Tips:
- Use React.memo to prevent unnecessary re-renders.
- Use PureComponent or
useMemo
,useCallback
. - Use code splitting and lazy loading.
- Minimize props and avoid large state updates.
40. What are error boundaries?
Description:
Error boundaries are React components that catch JavaScript errors in their child components and render a fallback UI instead of crashing the whole app.
Example:
class ErrorBoundary extends React.Component {
constructor() {
super();
this.state = { hasError: false };
}
static getDerivedStateFromError() {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong!</h1>;
}
return this.props.children;
}
}
41. What is propTypes
in React?
Description:propTypes
is a type-checking tool built into React to validate the props passed to a component. It helps catch bugs during development by ensuring components receive the correct type of data.
import PropTypes from 'prop-types';
function Greeting({ name, age }) {
return <p>Hello, {name}. You are {age} years old.</p>;
}
Greeting.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number
};
42. What is defaultProps
?
Description:defaultProps
allows you to specify default values for props in case they are not provided by the parent component.
function Button({ label }) {
return <button>{label}</button>;
}
Button.defaultProps = {
label: 'Click Me'
};
43. How do you handle events in React?
Description:
React uses camelCase for event names and passes an event handler function. You can use event objects (e.g., event.target.value
) just like in regular DOM events.
function Clicker() {
function handleClick(event) {
console.log('Clicked!', event);
}
return <button onClick={handleClick}>Click</button>;
}
44. What is the difference between inline and external CSS in React?
Feature | Inline CSS | External CSS |
---|---|---|
Syntax | Written in the component as objects | Written in separate .css files |
Scope | Component-scoped | Global or module-scoped |
Usage | Quick styling | Better for large projects |
const style = { color: 'blue', fontSize: '18px' };
function Title() {
return <h1 style={style}>Hello</h1>;
}
/* styles.css */
.title {
color: blue;
font-size: 18px;
}
import './styles.css';
function Title() {
return <h1 className="title">Hello</h1>;
}
45. Can React be used for mobile app development?
Yes.
Using React Native, you can build cross-platform mobile apps using React-like syntax, but the components render to native platform UI elements.
Example:
import { Text, View } from 'react-native';
export default function App() {
return (
<View>
<Text>Hello from React Native!</Text>
</View>
);
}
46. What is JSX transpilation?
Description:
JSX needs to be converted into plain JavaScript that browsers can understand. Tools like Babel transpile JSX to React.createElement()
calls during build time.
const element = <h1>Hello</h1>;
Transpiles to:
const element = React.createElement('h1', null, 'Hello');
47. What is a key
prop in React lists?
Description:
A key
prop uniquely identifies each element in a list. React uses it to determine which items changed, were added, or removed.
You should use a unique ID rather than index to avoid re-render bugs.
48. How do you pass data between components?
- Parent to Child: Use props
- Child to Parent: Use callback functions
- Between siblings or unrelated components: Use Context API or Redux
// Parent
function Parent() {
const sayHello = (name) => alert(`Hello, ${name}`);
return <Child onGreet={sayHello} />;
}
// Child
function Child({ onGreet }) {
return <button onClick={() => onGreet('Alice')}>Greet</button>;
}
49. What is the significance of the return
statement in functional components?
Description:
In React functional components, return
is required to output JSX (UI). Without it, nothing renders.
Example:
function Hello() {
return <h1>Hello, world!</h1>;
}
50. How do you debug React apps?
Tips:
- Use React Developer Tools extension (Chrome/Firefox) to inspect component props/state.
- Use console.log() to trace values.
- Use error boundaries to catch UI errors.
- Check browser dev tools and network tab for API calls.
- Use eslint-plugin-react for catching bugs via linting.
Top 5 Wearable Devices to Track Your Fitness and Health
In today’s…
Top System Design Interview-Design a Social Media Feed System (2025 Edition)
Overview A…
Design a URL Shortening Service
Overview We’ll…
Top 10 System Design Interview Questions (2025 Edition)
1. Design…
Top 50 Cloud Monitoring Interview Questions with Answers (2025 Edition)
1. What…
Top 50 Monitoring Tools Interview Questions with Answers
1. What…
Chamba’s Handicrafts and Himachali Culture — A Deep Dive
Introduction Chamba…
Camping and Homestays in Mandi: Your Gateway to Local Experiences
Introduction If…
Camping in Kullu-Manali: Best Campsites & Tips for Beginners
Introduction Imagine…