React.js is one of the most widely used JavaScript libraries for building dynamic and high-performance user interfaces. Whether you're preparing for an interview or starting your React journey, understanding the fundamentals is essential. In this article, we will cover the top 25 beginner-level React.js interview questions with detailed explanations and examples.
1. What is React.js, and why is it so popular?
React.js is an open-source JavaScript library developed by Facebook for building interactive and reusable UI components. It focuses on the "view" part of the Model-View-Controller (MVC) pattern, making UI updates more efficient and scalable.
Unlike traditional JavaScript frameworks that manipulate the DOM directly, React uses a Virtual DOM to improve performance and update the UI efficiently. This approach makes React ideal for building fast, responsive web applications.
Key Reasons for React's Popularity:
- Component-Based Architecture: React promotes reusable components, making UI development modular and maintainable.
- Virtual DOM: React uses an in-memory representation of the actual DOM to minimize updates and improve performance.
- Unidirectional Data Flow: Data flows in one direction, reducing complexity and making state management predictable.
- Huge Ecosystem & Community: With thousands of third-party libraries, React has extensive resources and a strong developer community.
Example: Simple React Component
import React from 'react';
function Welcome() {
return <h1>Hello, React!</h1>;
}
export default Welcome;
Key Takeaways:
- React.js is a library**, not a full-fledged framework.
- It optimizes UI updates through Virtual DOM**, making apps faster.
- Component-based architecture improves code reusability and maintainability**.
- React is declarative, making UI development more predictable and easier to debug**.
2. What are the key features of React?
React introduces several innovative features that make it a preferred choice for developers:
1. JSX (JavaScript XML): JSX allows developers to write HTML-like syntax within JavaScript, making UI code more readable.
2. Components: Everything in React is built as reusable, self-contained components, making development modular.
3. Virtual DOM: Instead of updating the real DOM directly, React first updates a lightweight in-memory representation and then applies only the necessary changes.
4. State Management: React provides a built-in useState hook for handling dynamic UI data.
5. Unidirectional Data Flow: Data in React always flows from parent to child**, ensuring predictable behavior.
Example: JSX in a React Component
import React from 'react';
function Greeting() {
const name = "John";
return <h1>Hello, {name}!</h1>;
}
export default Greeting;
Key Takeaways:
- React's Virtual DOM helps improve rendering performance.
- JSX makes UI code more readable and maintainable**.
- Component-based structure allows code reuse**.
3. What is JSX, and why is it used in React?
JSX (JavaScript XML) is a syntax extension for JavaScript that allows developers to write UI elements using HTML-like syntax.
Instead of writing complex `document.createElement` code, JSX allows us to define components in an easy-to-read format.
Why Use JSX?
- Improves Readability: JSX provides an HTML-like syntax that makes code easier to understand.
- Prevents XSS Attacks: JSX automatically escapes potentially dangerous content**, preventing cross-site scripting attacks.
- Enhances Performance: JSX is compiled into optimized JavaScript code, improving execution speed.
Example: Using JSX in a React Component
import React from 'react';
function JSXExample() {
return (
<div>
<h1>Welcome to React!</h1>
<p>This is an example of JSX syntax.</p>
</div>
);
}
export default JSXExample;
Key Takeaways:
- JSX is not required in React but makes UI development easier.
- JSX compiles to JavaScript functions before execution.
- JSX automatically escapes data, preventing security vulnerabilities**.
4. What is the Virtual DOM, and how does it work?
The Virtual DOM (VDOM) is a lightweight representation of the actual DOM that helps React update UI elements efficiently without unnecessary re-renders.
Instead of making changes directly to the real DOM (which is slow), React updates the Virtual DOM first, finds the differences, and then updates only the necessary elements in the real DOM.
How Virtual DOM Works:
- React creates a copy of the real DOM in memory.
- When the state or props change, React updates the Virtual DOM first.
- React compares the previous and new Virtual DOM using a process called "diffing"**.
- Only the changed elements are updated in the real DOM, minimizing performance overhead.
Example: React Virtual DOM in Action
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
Key Takeaways:
- The Virtual DOM is an in-memory representation of the real DOM.
- React only updates the changed elements**, improving performance.
- The diffing algorithm compares previous and current Virtual DOM versions.
- Virtual DOM reduces expensive direct DOM manipulations**, making React faster.
5. What is the difference between functional and class components?
React allows developers to create components in two ways: Functional Components and Class Components**.
Functional Components: These are simpler, stateless components that are written as JavaScript functions.
Class Components: These are ES6 classes that extend React.Component
and use lifecycle methods to manage state and side effects.
Key Differences:
Feature | Functional Component | Class Component |
---|---|---|
Definition | Uses JavaScript functions. | Uses ES6 class syntax. |
State Management | Uses useState and hooks. |
Uses this.state and setState . |
Lifecycle Methods | Uses hooks like useEffect . |
Uses methods like componentDidMount . |
Performance | More lightweight and optimized. | More overhead due to lifecycle methods. |
Usage | Recommended for modern React development. | Mostly used in legacy projects. |
Example: Functional Component
// Functional Component
function Greeting() {
return <h1>Hello, Functional Component!</h1>;
}
export default Greeting;
Example: Class Component
// Class Component
class GreetingClass extends React.Component {
render() {
return <h1>Hello, Class Component!</h1>;
}
}
export default GreetingClass;
Key Takeaways:
- Functional components are simpler and preferred for modern React development.
- Class components are still used in older React applications.
- React hooks (like
useState
anduseEffect
) make functional components powerful. - Functional components reduce boilerplate code and improve readability.
6. What are props in React, and how are they used?
Props (short for "properties") are read-only data passed from a parent component to a child component in React. Props make components reusable by allowing dynamic values to be passed.
Key Characteristics of Props:
- Immutable: Props cannot be modified by the child component.
- Reusable: Components can accept different props to render different outputs.
- Unidirectional: Props follow one-way data flow (from parent to child).
Example: Passing Props to a Component
// Parent Component
import React from 'react';
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
function App() {
return <Greeting name="John" />;
}
export default App;
Key Takeaways:
- Props allow dynamic values to be passed to components.
- They cannot be changed inside the child component.
- Props help make components reusable.
7. What is state in React, and how is it different from props?
State is a built-in object that allows React components to store and manage dynamic data that can change over time.
Props vs. State:
- Props: Passed from parent to child and are read-only.
- State: Managed within the component and can be updated using
setState
(class components) oruseState
(functional components).
Example: Using State in a Functional Component
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
Key Takeaways:
- State allows components to track changing data.
useState
is used for managing state in functional components.- Changing state triggers a re-render of the component.
8. What are controlled and uncontrolled components?
React handles form inputs in two ways: controlled and uncontrolled components.
Controlled Components: React controls the form input using state.
Example: Controlled Component
import React, { useState } from 'react';
function ControlledInput() {
const [inputValue, setInputValue] = useState('');
return (
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
);
}
export default ControlledInput;
Key Takeaways:
- Controlled components store input values in React state.
- Uncontrolled components store input values in the DOM.
9. What are React Hooks, and why are they useful?
React Hooks are functions that let functional components use state and lifecycle features without needing class components. Introduced in React 16.8, they have revolutionized state management and side effect handling in React applications.
Why use React Hooks?
- Allow functional components to manage state (
useState
). - Enable handling of side effects (
useEffect
). - Reduce complexity and make code more readable compared to class components.
Commonly Used Hooks:
useState
– Manages component state.useEffect
– Handles side effects such as fetching data.useContext
– Accesses values from the React Context API.useRef
– Maintains references to DOM elements or values.
Example: Using useState
and useEffect
import React, { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds((prevSeconds) => prevSeconds + 1);
}, 1000);
return () => clearInterval(interval); // Cleanup function
}, []);
return <p>Timer: {seconds} seconds</p>;
}
export default Timer;
Key Takeaways:
- Hooks enable state and lifecycle management inside functional components.
useState
replacesthis.state
in class components.useEffect
replaces lifecycle methods likecomponentDidMount
.
10. What is the useEffect
Hook, and how does it work?
The useEffect
Hook is used in React to handle side effects like fetching data, setting up subscriptions, or updating the DOM.
It runs after the component renders and can be configured to run on specific state changes.
Common Use Cases:
- Fetching data from an API.
- Listening for browser events (e.g., window resize).
- Managing timers or intervals.
Example: Fetching Data with useEffect
import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(data => setData(data.slice(0, 5))); // Fetch first 5 items
}, []);
return (
<ul>
{data.map(post => <li key={post.id}>{post.title}</li>)}
</ul>
);
}
export default DataFetcher;
Key Takeaways:
- The
useEffect
Hook runs after the component renders. - It replaces lifecycle methods like
componentDidMount
andcomponentDidUpdate
. - The dependency array
[]
determines when the effect runs.
11. What is the significance of the key
prop in React?
The key
prop in React helps identify which items have changed, been added, or removed when rendering lists. It improves performance by optimizing the reconciliation process.
Why is the key
prop important?
- Helps React efficiently update and re-render components.
- Avoids unnecessary re-renders, enhancing performance.
- Prevents UI bugs when dynamically adding or removing elements.
Example: Using keys in a list
import React from 'react';
function ItemList({ items }) {
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
export default ItemList;
Key Takeaways:
- Keys must be unique among siblings but can repeat across different lists.
- Using array indexes as keys should be avoided unless elements are static.
12. What is prop drilling in React, and how can it be avoided?
Prop drilling occurs when data is passed from a parent component to a deeply nested child component through multiple intermediate components.
Example: Prop drilling
import React from 'react';
function GrandChild({ message }) {
return <p>{message}</p>;
}
function Child({ message }) {
return <GrandChild message={message} />;
}
function Parent() {
return <Child message="Hello from Parent!" />;
}
export default Parent;
Ways to avoid prop drilling:
- Context API: Share data globally without passing props manually.
- State management libraries (Redux, Zustand): Manage shared state efficiently.
Key Takeaways:
- Prop drilling can lead to excessive prop passing and reduced maintainability.
- The Context API and state management libraries help avoid this issue.
13. What are React fragments, and why are they used?
React fragments (<React.Fragment>
or shorthand <>
) allow grouping multiple elements without adding an extra DOM node.
Why use React Fragments?
- Prevents unnecessary wrapper
div
elements. - Improves performance by reducing DOM nodes.
- Required when returning multiple elements in a component.
Example: Using React Fragments
import React from 'react';
function Example() {
return (
<>
<h1>Heading</h1>
<p>This is a paragraph.</p>
</>
);
}
export default Example;
Key Takeaways:
- React fragments are useful when returning multiple elements.
- The shorthand syntax
<>...</>
is a cleaner alternative to<React.Fragment>
.
14. What are higher-order components (HOC) in React?
A higher-order component (HOC) is a function that takes a component as input and returns a new enhanced component.
Why use HOCs?
- Code reusability by wrapping logic in a single place.
- Enhancing components without modifying their original structure.
Example: Creating an HOC
import React from 'react';
function withLogging(WrappedComponent) {
return function WithLogging(props) {
console.log("Component rendered:", WrappedComponent.name);
return <WrappedComponent {...props} />;
};
}
function HelloWorld() {
return <h1>Hello, World!</h1>;
}
const EnhancedComponent = withLogging(HelloWorld);
export default EnhancedComponent;
15. What are React Portals, and when should you use them?
React Portals allow rendering a component outside its parent DOM hierarchy. This is particularly useful for modals, popups, or tooltips that need to break out of the parent’s CSS constraints.
Why use React Portals?
- Bypasses parent styling limitations: Ensures modals/popups are not affected by parent overflow or z-index.
- Enhances accessibility: Useful for screen readers and ARIA roles.
- Keeps logical component structure: Even though rendered outside, components remain within React’s tree.
Example: Using React Portals
import React from 'react';
import ReactDOM from 'react-dom';
function Modal({ children }) {
return ReactDOM.createPortal(
<div class="modal">{children}</div>,
document.getElementById('modal-root')
);
}
function App() {
return (
<div>
<h1>Main App Content</h1>
<Modal>
<p>This is inside a portal!</p>
</Modal>
</div>
);
}
export default App;
Before using React Portals, make sure to include a separate root element in your index.html
:
<body>
<div id="root"></div>
<div id="modal-root"></div> <!-- Portal Target -->
</body>
Key Takeaways:
- Portals help render components outside the main app hierarchy.
- They are commonly used for modals, tooltips, and overlays.
- Requires a separate
div
in theindex.html
for rendering.
16. What is the Context API in React, and how does it work?
The Context API is a built-in feature in React that allows **data sharing across components** without passing props manually through each level (avoiding "prop drilling").
Why use the Context API?
- Eliminates prop drilling: Allows global state sharing.
- Reduces unnecessary re-renders: Only components consuming the context update when the value changes.
- Improves code maintainability: Ideal for themes, authentication, and global state.
Example: Using the Context API
import React, { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
function ThemeComponent() {
const theme = useContext(ThemeContext);
return <p>Current Theme: {theme}</p>;
}
function App() {
return (
<ThemeContext.Provider value="dark">
<ThemeComponent />
</ThemeContext.Provider>
);
}
export default App;
Key Takeaways:
- The Context API simplifies global state management.
useContext
allows components to consume context values without prop drilling.- Alternatives like Redux or Zustand provide more advanced state management solutions.
17. What is the difference between useEffect
and useLayoutEffect
?
Both useEffect
and useLayoutEffect
are React hooks used for handling side effects, but they differ in execution timing.
Key Differences:
useEffect
runs after the component renders.useLayoutEffect
runs before the browser paints the screen.useLayoutEffect
is useful for DOM measurements and animations.
Example: Using useEffect
vs useLayoutEffect
import React, { useEffect, useLayoutEffect, useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('useEffect triggered:', count);
}, [count]);
useLayoutEffect(() => {
console.log('useLayoutEffect triggered:', count);
}, [count]);
return <button onClick={() => setCount(count + 1)}>Click me</button>;
}
export default Example;
Key Takeaways:
useEffect
is used for API calls and data fetching.useLayoutEffect
is used for DOM layout calculations before painting.- Avoid
useLayoutEffect
for performance-heavy tasks.
18. What is React.memo
, and how does it improve performance?
React.memo
is a higher-order component (HOC) that optimizes functional components by preventing unnecessary re-renders.
Why use React.memo?
- Prevents re-rendering when props haven’t changed.
- Improves performance in large-scale applications.
Example: Using React.memo
import React, { useState, memo } from 'react';
const MemoizedComponent = memo(({ name }) => {
console.log("Rendered");
return <h1>Hello, {name}!</h1>;
});
function App() {
const [count, setCount] = useState(0);
return (
<div>
<MemoizedComponent name="John" />
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default App;
Key Takeaways:
React.memo
avoids re-renders if props remain unchanged.- Best for optimizing performance in large React apps.
19. What is the useCallback
Hook, and when should you use it?
The useCallback
Hook is a React optimization technique that memoizes functions, preventing them from being re-created unnecessarily on every render.
Why use useCallback
?
- Prevents function re-creation on every render.
- Improves performance in components with frequent re-renders.
- Optimizes child components that depend on a stable function reference.
Example: Using useCallback
to Prevent Unnecessary Re-Creation
import React, { useState, useCallback } from 'react';
function Child({ onClick }) {
console.log("Child Rendered");
return <button onClick={onClick}>Click me</button>;
}
function Parent() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
console.log("Button Clicked");
}, []);
return (
<div>
<Child onClick={handleClick} />
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Parent;
Key Takeaways:
useCallback
prevents unnecessary function re-creation on each render.- Best used in performance-critical applications to optimize re-renders.
- Works well with memoized components to improve efficiency.
20. What is the useRef
Hook, and how is it used?
The useRef
Hook creates a reference that persists across renders without causing re-renders. It is commonly used for accessing DOM elements or storing mutable values.
Why use useRef
?
- Allows direct DOM manipulation (e.g., focusing an input field).
- Stores values without triggering re-renders.
- Can hold a reference to a component instance or an interval.
Example: Using useRef
to Access an Input Field
import React, { useRef } from 'react';
function InputFocus() {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={handleClick}>Focus Input</button>
</div>
);
}
export default InputFocus;
Key Takeaways:
useRef
allows direct DOM access without triggering a re-render.- Useful for storing mutable values across renders.
- Commonly used for handling focus, animations, or timers.
21. What is React Router, and why is it used?
React Router is a popular library used for handling client-side navigation in React applications. It enables the creation of single-page applications (SPAs) with multiple views while keeping the page dynamically updated without requiring a full reload.
Why use React Router?
- Enables declarative navigation using components.
- Provides dynamic routing with URL parameters.
- Enhances performance by preventing full-page reloads.
Example: Basic React Router Setup
import React from 'react';
import { BrowserRouter as Router, Route, Routes, Link } from 'react-router-dom';
function Home() {
return <h1>Home Page</h1>;
}
function About() {
return <h1>About Page</h1>;
}
function App() {
return (
<Router>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
}
export default App;
Key Takeaways:
- React Router enables client-side navigation without full-page reloads.
- Uses
<Routes>
and<Route>
to define navigation paths. <Link>
replaces traditional anchor tags for smooth navigation.
22. What is lazy loading in React?
Lazy loading is a technique that loads components only when needed, improving performance by reducing initial load time.
Why use lazy loading?
- Speeds up page load by only loading necessary components.
- Reduces unnecessary downloads of unused code.
Example: Using React.lazy
for Lazy Loading
import React, { lazy, Suspense } from 'react';
const LazyComponent = lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<p>Loading...</p>}>
<LazyComponent />
</Suspense>
);
}
export default App;
Key Takeaways:
- Lazy loading improves performance by deferring component loading.
React.lazy
allows asynchronous component loading.<Suspense>
provides a fallback UI while the component loads.
23. What are error boundaries in React?
Error boundaries are React components that catch JavaScript errors anywhere in the component tree and display a fallback UI instead of crashing the entire app.
Example: Creating an Error Boundary
import React, { Component } from 'react';
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.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>
<ComponentThatMightFail />
</ErrorBoundary>
);
}
export default App;
Key Takeaways:
- Error boundaries catch errors in child components and prevent crashes.
- They work only with class components, not functional components.
- Use them to handle UI errors gracefully without breaking the entire app.
24. What is reconciliation in React?
Reconciliation is the process React uses to efficiently update the UI when a component’s state or props change. Instead of re-rendering the entire DOM, React compares the updated Virtual DOM with the previous version and only updates the necessary parts.
How does reconciliation work?
- React creates a new Virtual DOM when a component’s state or props change.
- It compares the new Virtual DOM with the previous Virtual DOM using a process called diffing.
- React updates only the changed elements in the real DOM instead of re-rendering the entire page.
Example: React Reconciliation in Action
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
Key Takeaways:
- Reconciliation makes React efficient by only updating changed elements.
- React's diffing algorithm compares Virtual DOM versions.
- Helps in building high-performance applications with minimal DOM updates.
25. What is React’s Strict Mode, and what are its benefits?
Strict Mode is a tool in React that helps developers identify potential issues in their applications. It enables extra checks and warnings during development but has no impact on the production build.
Why use Strict Mode?
- Detects unsafe lifecycle methods in class components.
- Warns about side effects in useEffect that might cause bugs.
- Ensures that legacy code follows modern best practices.
Example: Enabling Strict Mode
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
Key Takeaways:
- Strict Mode helps detect potential problems in development.
- It does not affect production builds.
- Useful for identifying deprecated lifecycle methods and unsafe effects.

No comments: