1. What is React?

React is a JavaScript library used for building user interfaces, especially for single-page applications (SPAs).

Key Idea

It allows developers to build UI using reusable components and efficiently update the UI when data changes.

Developed By

Facebook (Meta)

Core Concept

UI = Function(State)

Why React?

  • Faster rendering using Virtual DOM
  • Component-based architecture
  • Declarative approach

2. What are the Main Features of React?

Component-Based Architecture

UI is divided into reusable components. Each component manages its own logic.

Virtual DOM

Improves performance by reducing direct DOM manipulation.

Declarative UI

Developers describe what the UI should look like.

JSX

Allows writing HTML-like syntax inside JavaScript.

One-Way Data Binding

Data flows from parent to child.

Reusability

Components can be reused across the application.

3. What is JSX?

JSX (JavaScript XML) is a syntax extension that allows writing HTML-like code inside JavaScript.

Example

Key Points

  • Optional but widely used
  • Improves readability
  • Compiled into JavaScript

4. How does JSX Work?

Behind the Scenes

JSX is transpiled into JavaScript using tools like Babel.

Example Conversion


Converts to:




const element = React.createElement("h1", null, "Hello");

Process Flow

  1. Developer writes JSX
  2. Babel compiles JSX
  3. Converts to React.createElement()
  4. Creates Virtual DOM object

5. What is the Virtual DOM?

Definition

The Virtual DOM is a lightweight copy of the real DOM stored in memory.

Purpose

  • Improve performance
  • Reduce costly DOM updates

How It Works

React creates a virtual representation, compares it with the previous version, and updates only the changed parts.


6. How does React Update the UI?

Step-by-Step Process

  1. State or props change
  2. React creates a new Virtual DOM
  3. Compares with previous Virtual DOM (diffing)
  4. Calculates minimal changes (reconciliation)
  5. Updates only required parts in the real DOM

Key Benefit

Efficient and fast UI updates


7. What is a React Component?

Definition

A React component is a reusable piece of UI.

Types

Functional Components




function Welcome() {
return <h1>Hello</h1>;
}

Class Components




class Welcome extends React.Component {
render() {
return <h1>Hello</h1>;
}
}

Key Characteristics

  • Reusable
  • Independent
  • Accept inputs (props)

8. Difference Between React Element and Component

FeatureReact ElementReact Component
DefinitionPlain object describing UIFunction/Class returning elements
NatureImmutableReusable logic
Example<h1>Hello</h1>function App() {}
PurposeUI building blockUI logic + structure

Summary

Element = What to render
Component = How to render


9. What are Props in React?

Definition

Props (Properties) are inputs passed from parent to child components.

Example




function Greeting(props) {
return <h1>Hello {props.name}</h1>;
}

<Greeting name="Jitendra" />

Key Features

  • Read-only (immutable)
  • Used for component communication
  • Passed as attributes

10. What is State in React?

Definition

State is a built-in object used to store dynamic data in a component.

Example




const [count, setCount] = useState(0);

Key Features

  • Mutable
  • Managed within the component
  • Triggers re-render on update

Props vs State

FeaturePropsState
MutabilityImmutableMutable
OwnershipParentComponent
PurposePass dataManage internal data

11. What is the difference between props and state?

Definition

Props and State are both used to manage data in React, but they serve different purposes.

Props

  • Passed from parent to child
  • Read-only (immutable)
  • Used for communication between components

State

  • Managed within the component
  • Mutable (can be updated)
  • Used for dynamic data

Key Differences

FeaturePropsState
MutabilityImmutableMutable
OwnershipParentComponent
PurposePass dataManage internal data
UpdateCannot be changed directlyCan be updated using setState/useState

Summary

Props are external inputs, while state is internal data that controls component behavior.


12. What is a Functional Component?

Definition

A functional component is a JavaScript function that returns JSX.

Example




function Welcome() {
return <h1>Hello</h1>;
}

Key Features

  • Simple and lightweight
  • Uses Hooks for state and lifecycle
  • Easier to read and test

Modern Usage

Functional components are now the standard in React development.


13. What is a Class Component?

Definition

A class component is a JavaScript class that extends React.Component and contains a render method.

Example




class Welcome extends React.Component {
render() {
return <h1>Hello</h1>;
}
}

Key Features

  • Uses lifecycle methods
  • Has built-in state management
  • More verbose than functional components

14. What is the difference between Functional and Class Components?

Comparison

FeatureFunctional ComponentClass Component
SyntaxFunctionES6 Class
StateuseState Hookthis.state
LifecycleuseEffect HookLifecycle methods
Code ComplexitySimpleMore complex
PerformanceSlightly betterSlightly heavier

Summary

Functional components are modern, concise, and preferred.
Class components are older and mainly used in legacy code.


15. What are Fragments in React?

Definition

Fragments allow grouping multiple elements without adding extra nodes to the DOM.

Example




<>
<h1>Title</h1>
<p>Description</p>
</>

Why Use Fragments?

  • Avoid unnecessary wrapper elements (like div)
  • Cleaner DOM structure
  • Better performance

16. What is the purpose of the key prop?

Definition

The key prop is used to uniquely identify elements in a list.

Example




items.map(item => <li key={item.id}>{item.name}</li>)

Purpose

  • Helps React identify which items changed
  • Improves rendering performance
  • Enables efficient updates

17. What happens if we use array index as key?

Behavior

Using index as key can lead to incorrect UI updates.

Problem Scenario

  • When items are added, removed, or reordered
  • React may reuse wrong components

Example Issue

  • Input fields may lose focus or show wrong data

Conclusion

  • Avoid index as key if list order can change
  • Use unique IDs instead

18. What are Controlled Components?

Definition

Controlled components are form elements whose value is controlled by React state.

Example




const [name, setName] = useState("");

<input value={name} onChange={e => setName(e.target.value)} />

Key Features

  • React controls input value
  • Single source of truth
  • Easier validation and debugging

19. What are Uncontrolled Components?

Definition

Uncontrolled components store their own state in the DOM.

Example




const inputRef = useRef();

<input ref={inputRef} />

Key Features

  • Uses refs to access values
  • Less control from React
  • Simpler but less flexible

20. How does React handle forms?

Approach

React handles forms using controlled or uncontrolled components.

Controlled Approach

  • Form data is stored in state
  • Updated via onChange handlers

Example




const [email, setEmail] = useState("");

<form>
<input value={email} onChange={e => setEmail(e.target.value)} />
</form>

Uncontrolled Approach

  • Uses refs to access form values
  • DOM handles state

Form Handling Features

  • Event handling (onChange, onSubmit)
  • Validation using state
  • Full control over input behavior

Best Practice

Use controlled components for better control and predictability.

21. What is Event Handling in React?

Definition

Event handling in React refers to the process of responding to user interactions such as clicks, form inputs, mouse movements, etc.

Key Characteristics

  • Uses camelCase naming (e.g., onClick, onChange)
  • Passes functions instead of strings
  • Follows a declarative approach

Example




function Button() {
function handleClick() {
console.log("Button clicked");
}

return <button onClick={handleClick}>Click Me</button>;
}

Key Points

  • Events are bound directly in JSX
  • No need for addEventListener
  • Works consistently across browsers

22. What are Synthetic Events?

Definition

Synthetic events are React’s wrapper around native browser events.

Purpose

  • Ensure cross-browser compatibility
  • Provide consistent behavior

Example




function handleClick(event) {
console.log(event.type); // Synthetic event
}

Key Features

  • Same interface as native events
  • Normalized across all browsers
  • Includes methods like preventDefault() and stopPropagation()

23. What is Conditional Rendering in React?

Definition

Conditional rendering allows displaying different UI elements based on conditions.

Common Techniques

Using if/else




if (isLoggedIn) {
return <h1>Welcome</h1>;
} else {
return <h1>Please Login</h1>;
}

Using ternary operator




{isLoggedIn ? <h1>Welcome</h1> : <h1>Please Login</h1>}

Using logical AND




{isLoggedIn && <h1>Welcome</h1>}

Use Cases

  • Authentication UI
  • Feature toggles
  • Dynamic content display

24. How do you render a list in React?

Approach

Use JavaScript’s map() function to iterate over arrays.

Example




const items = ["Apple", "Banana", "Mango"];

<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>

Important Note

Always provide a unique key prop for each element.

Benefits

  • Efficient rendering
  • Easy to manage dynamic lists

25. What are Default Props?

Definition

Default props are used to assign default values to props if they are not provided.

Example




function Greeting({ name = "Guest" }) {
return <h1>Hello {name}</h1>;
}

Alternative (older syntax)




Greeting.defaultProps = {
name: "Guest"
};

Benefits

  • Prevents undefined values
  • Makes components more robust

26. What is Prop Drilling?

Definition

Prop drilling is the process of passing data through multiple layers of components even if intermediate components don’t need it.

Problem

  • Makes code harder to maintain
  • Increases complexity

Example

Parent → Child → Grandchild (passing props at each level)

Solution

  • Context API
  • State management libraries (Redux, Zustand)

27. What is Lifting State Up?

Definition

Lifting state up means moving state to the closest common ancestor of multiple components.

Purpose

  • Share data between components
  • Maintain a single source of truth

Example Scenario

Two input fields need to share the same data → move state to parent.

Benefits

  • Better data synchronization
  • Improved state management

28. What are React Hooks?

Definition

Hooks are functions that allow using state and lifecycle features in functional components.

Common Hooks

  • useState
  • useEffect
  • useContext
  • useRef

Example




const [count, setCount] = useState(0);

Benefits

  • Simpler code
  • Reusable logic
  • No need for class components

29. Why were Hooks introduced?

Problems Before Hooks

  • Complex class components
  • Difficult to reuse logic
  • Lifecycle methods were hard to manage

Purpose of Hooks

  • Enable state in functional components
  • Simplify code structure
  • Improve logic reuse

Benefits

  • Cleaner and shorter code
  • Better separation of concerns
  • Easier testing and maintenance

30. What is useState?

Definition

useState is a Hook used to add state to functional components.

Syntax




const [state, setState] = useState(initialValue);

Example




const [count, setCount] = useState(0);

<button onClick={() => setCount(count + 1)}>
{count}
</button>

How It Works

  • Returns current state value
  • Returns a function to update state
  • Triggers re-render on update

Key Features

  • Supports multiple state variables
  • Works asynchronously
  • Maintains state between renders 

31. What is useEffect?

Definition

useEffect is a React Hook used to perform side effects in functional components.

Purpose

Handle operations like:

  • API calls
  • DOM manipulation
  • Subscriptions
  • Timers

Syntax




useEffect(() => {
// side effect logic
}, []);

Example




useEffect(() => {
console.log("Component mounted");
}, []);

Key Behavior

  • Runs after render
  • Can run on mount, update, or unmount

32. What is the dependency array in useEffect?

Definition

The dependency array controls when the useEffect function runs.

Cases

No dependency array




useEffect(() => {
console.log("Runs on every render");
});

Empty array




useEffect(() => {
console.log("Runs once (on mount)");
}, []);

With dependencies




useEffect(() => {
console.log("Runs when count changes");
}, [count]);

Key Insight

React compares dependency values and re-runs effect only when they change.


33. What are side effects in React?

Definition

Side effects are operations that interact with the outside world or affect something outside the component.

Examples

  • Fetching data from API
  • Updating DOM manually
  • Setting timers
  • Subscribing to events

Why Important

React components should be pure functions → side effects must be handled separately using useEffect.


34. What are keys in React lists?

Definition

Keys are unique identifiers assigned to elements in a list.

Example




items.map(item => (
<li key={item.id}>{item.name}</li>
));

Purpose

  • Helps React track changes
  • Improves performance
  • Ensures correct UI updates

Best Practice

Use stable, unique IDs instead of indexes.


35. What is JSX transpiled into?

Definition

JSX is converted into JavaScript function calls.

Example




const element = <h1>Hello</h1>;

Transpiles to:




const element = React.createElement("h1", null, "Hello");

Tool Used

Babel (transpiler)

Key Insight

JSX is syntactic sugar over React.createElement.


36. What is ReactDOM?

Definition

ReactDOM is a library that provides DOM-specific methods for rendering React components in the browser.

Example




import ReactDOM from "react-dom/client";

ReactDOM.createRoot(document.getElementById("root")).render(<App />);

Responsibilities

  • Rendering components to DOM
  • Updating DOM efficiently
  • Managing root elements

37. What is the difference between React and ReactDOM?

React

  • Core library
  • Handles components, state, logic

ReactDOM

  • Handles rendering to browser DOM
  • Connects React with web environment

Comparison

FeatureReactReactDOM
RoleUI logicDOM rendering
PlatformPlatform-independentWeb-specific
ExampleComponents, Hooksrender(), createRoot()

Summary

React = Brain
ReactDOM = Bridge to browser


38. What are Stateless Components?

Definition

Stateless components are components that do not manage state.

Characteristics

  • Receive data via props
  • Pure functions
  • No internal data changes

Example




function Greeting({ name }) {
return <h1>Hello {name}</h1>;
}

Benefit

  • Simple and predictable

39. What are Stateful Components?

Definition

Stateful components are components that manage their own state.

Characteristics

  • Maintain internal data
  • Can update UI dynamically
  • Use state (useState or this.state)

Example




const [count, setCount] = useState(0);

Benefit

  • Enables interactive UI

40. What are Inline Conditional Expressions?

Definition

Inline conditional expressions allow rendering UI directly inside JSX using conditions.

Common Methods

Ternary operator




{isLoggedIn ? <h1>Welcome</h1> : <h1>Login</h1>}

Logical AND




{isLoggedIn && <h1>Welcome</h1>}

Use Cases

  • Show/hide elements
  • Conditional UI rendering
  • Feature toggles

Advantage

  • Cleaner and concise code 

41. What is the children prop?

Definition

children is a special prop in React used to pass content between opening and closing tags of a component.

Example




function Wrapper({ children }) {
return <div className="box">{children}</div>;
}

<Wrapper>
<h1>Hello</h1>
<p>World</p>
</Wrapper>

Key Features

  • Automatically available in every component
  • Enables component composition
  • Can pass JSX, strings, or other components

Use Case

Building reusable layout components like modals, cards, wrappers


42. What is React.StrictMode?

Definition

React.StrictMode is a development tool used to highlight potential problems in an application.

Example




<React.StrictMode>
<App />
</React.StrictMode>

Key Features

  • Detects unsafe lifecycle methods
  • Identifies side effects
  • Warns about deprecated APIs
  • Runs extra checks in development

Important Note

  • Does not affect production
  • Used only for debugging and best practices

43. What are PropTypes?

Definition

PropTypes are used for type-checking props in React components.

Example




import PropTypes from "prop-types";

function User({ name, age }) {
return <h1>{name} - {age}</h1>;
}

User.propTypes = {
name: PropTypes.string,
age: PropTypes.number
};

Purpose

  • Validate data types
  • Catch bugs early
  • Improve code reliability

Note

Mostly used in JavaScript (TypeScript is preferred now)


44. What is create-react-app?

Definition

create-react-app (CRA) is a toolchain that sets up a React project with zero configuration.

Features

  • Preconfigured build setup
  • Includes Webpack, Babel
  • Development server ready
  • Hot reloading

Command




npx create-react-app my-app

Current Trend

Many developers now prefer Vite or Next.js over CRA.


45. What is the difference between HTML and React event handling?

HTML Event Handling




<button onclick="handleClick()">Click</button>

React Event Handling




<button onClick={handleClick}>Click</button>

Key Differences

FeatureHTMLReact
NaminglowercasecamelCase
Valuestringfunction
Event TypeNative eventsSynthetic events

Summary

React uses a more consistent and JavaScript-based approach.


46. What are Portals in React?

Definition

Portals allow rendering components outside the parent DOM hierarchy.

Example




ReactDOM.createPortal(<Modal />, document.getElementById("modal-root"));

Use Cases

  • Modals
  • Tooltips
  • Popups

Benefit

Avoids CSS issues like overflow and z-index conflicts


47. What are Refs in React?

Definition

Refs provide a way to access DOM elements directly.

Example




const inputRef = useRef();

<input ref={inputRef} />

Use Cases

  • Focus input fields
  • Access DOM properties
  • Integrate with third-party libraries

Key Note

Avoid overusing refs; prefer declarative approach.


48. What is useRef?

Definition

useRef is a Hook that returns a mutable reference object.

Example

Key Features

  • Persists value across renders
  • Does not trigger re-render
  • Used for DOM access and storing values

Use Cases

  • Store previous values
  • Access DOM nodes
  • Manage timers

49. What is Memoization?

Definition

Memoization is an optimization technique that caches results of expensive computations.

Purpose

  • Avoid unnecessary recalculations
  • Improve performance

Example Concept

If inputs don’t change → reuse previous result

In React

  • useMemo
  • React.memo

50. What is React.memo?

Definition

React.memo is a higher-order component that prevents unnecessary re-renders.

Example


How It Works
  • Performs shallow comparison of props
  • Re-renders only if props change

Benefits

  • Performance optimization
  • Reduces rendering cost

Limitation

  • Only works for functional components
  • Shallow comparison may not detect deep changes