0% found this document useful (0 votes)
9 views16 pages

question(HTML,CSS,JS,REACT)

The document contains a comprehensive set of 60 questions and answers covering HTML, CSS, and JavaScript. It addresses fundamental concepts, differences between elements and attributes, as well as best practices for web development. Each section provides clear explanations and examples to enhance understanding of web technologies.

Uploaded by

jaymahato10125
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views16 pages

question(HTML,CSS,JS,REACT)

The document contains a comprehensive set of 60 questions and answers covering HTML, CSS, and JavaScript. It addresses fundamental concepts, differences between elements and attributes, as well as best practices for web development. Each section provides clear explanations and examples to enhance understanding of web technologies.

Uploaded by

jaymahato10125
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

HTML (20 Questions with Answers):

1. What is HTML?
o Answer: HTML (HyperText Markup Language) is the standard markup
language for creating web pages. It provides the structure and content of a
website.
2. What are the basic elements of an HTML document?
o Answer: The basic elements are <!DOCTYPE html>, <html>, <head>,
<title>, and <body>.
3. What is the difference between <div> and <span>?
o Answer: <div> is a block-level element that creates a container and takes up
the full width available. <span> is an inline-level element used to mark up a
small section of text or other inline elements within a block-level element.
4. What are semantic HTML tags? Give some examples.
o Answer: Semantic HTML tags provide meaning to the structure of the page,
making it more understandable for both developers and search engines.
Examples include <article>, <nav>, <aside>, <header>, <footer>, and
<main>.
5. Explain the difference between id and class attributes in HTML.
o Answer: id is a unique identifier for a single element within a document.
class is used to group multiple elements together, allowing you to apply the
same styles or JavaScript to them.
6. What is the purpose of the <head> element in HTML?
o Answer: The <head> element contains meta-information about the HTML
document, such as the character set, page title (displayed in the browser tab),
links to CSS files, and scripts.
7. What are the different types of lists in HTML? How do you create them?
o Answer: There are three main types:
 Ordered lists (<ol>): Items are numbered.
 Unordered lists (<ul>): Items are bulleted.
 Description lists (<dl>): Used to display terms and their descriptions
(<dt>, <dd>).
8. Explain the difference between <a> and <button> elements. When would you use
each?
o Answer: <a> creates a hyperlink to another page or resource. Use it for
navigation. <button> creates an interactive button that performs an action
when clicked (often triggered by JavaScript).
9. How do you embed images and videos in an HTML page?
o Answer: Use the <img> tag for images (<img src="image.jpg"
alt="Description">) and the <video> tag for videos (<video
src="video.mp4" controls></video>).
10. What are HTML forms? How do you create them?
o Answer: HTML forms are used to collect user input. They are created using
the <form> element, which contains various input elements like <input>,
<textarea>, <select>, and <button>.
11. Explain the purpose of the different input types in HTML forms.
o Answer: Input types define the kind of data the user can enter (e.g., text,
password, email, number, radio, checkbox, submit).
12. What is the purpose of the <label> tag in HTML forms?
o Answer: The <label> tag associates a text label with a form control (using
the for attribute), improving accessibility by allowing users to click on the
label to focus on the input.
13. What is the purpose of the <iframe> tag? When might you use it?
o Answer: The <iframe> tag embeds another HTML document within the
current page. It's often used to display content from external websites, like
maps or videos.
14. What is the difference between HTML 4 and HTML 5?
o Answer: HTML 5 introduced new semantic elements, improved multimedia
support (audio and video tags), better form controls, the <canvas> element for
drawing, and improved accessibility features.
15. What are some new semantic tags introduced in HTML 5?
o Answer: Examples include <article>, <aside>, <nav>, <header>,
<footer>, <section>, and <main>.
16. What is the purpose of the <canvas> element?
o Answer: The <canvas> element provides a way to draw graphics, animations,
and other visual elements on a web page using JavaScript.
17. What are HTML entities? Give some examples.
o Answer: HTML entities are used to display characters that are reserved in
HTML or are difficult to type directly. Examples: &lt; for <, &gt; for >,
&amp; for &, &nbsp; for a non-breaking space.
18. How do you structure a basic HTML page for SEO?
o Answer: Use semantic tags to structure content, provide a relevant <title>,
use descriptive meta tags (especially description), use heading tags ( <h1> to
<h6>) appropriately, and use meaningful alt text for images.
19. What is the purpose of the viewport meta tag?
o Answer: The viewport meta tag controls the initial scale and width of the
viewport on different devices, ensuring the page renders correctly on various
screen sizes (crucial for responsive design).
20. Explain the concept of accessibility in HTML. What are some best practices?
o Answer: Accessibility means designing websites that are usable by people
with disabilities. Best practices include using semantic HTML, providing alt
text for images, using labels for form controls, ensuring keyboard navigation,
and providing transcripts for audio and captions for video.

CSS (20 Questions with Answers):

1. What is CSS?
o Answer: CSS (Cascading Style Sheets) is a stylesheet language used to
describe the presentation of a document written in a markup language like
HTML. It controls the layout, colors, fonts, and other visual aspects of a
website.
2. What are the different ways to include CSS in an HTML document? What are
the advantages and disadvantages of each?
o Answer:
 Inline CSS: Directly within HTML elements using the style
attribute.
 Advantage: Quick for applying styles to a single element.
 Disadvantage: Not maintainable or scalable, separates
structure and presentation poorly.
 Internal CSS: Within the <style> tags in the <head> section of the
HTML document.
 Advantage: Useful for styling a single page.
 Disadvantage: Less maintainable for larger sites, still mixes
structure and presentation to some extent.
 External CSS: Linked using the <link> tag in the <head> section,
pointing to a separate .css file.
 Advantage: Best for maintainability, scalability, and separation
of concerns. Styles can be applied consistently across multiple
pages.
 Disadvantage: Requires an extra HTTP request to load the
stylesheet (though this is usually cached).
3. What is the CSS box model? Explain its components.
o Answer: The CSS box model describes the rectangular boxes that are
generated for elements in the document tree and laid out according to visual
formatting model. Its components are:
 Content: The actual content of the element (text, images, etc.).
 Padding: Space around the content, inside the border.
 Border: A line surrounding the padding and content.
 Margin: Space around the border, separating the element from its
neighbors.
4. What is the difference between block and inline elements?
o Answer: block elements take up the full width available and start on a new
line (e.g., <div>, <p>, <h1>). inline elements only take up as much width as
necessary and do not start on a new line (e.g., <span>, <a>, <em>).
5. What are CSS selectors? List some common types of selectors.
o Answer: CSS selectors are patterns used to select the HTML elements you
want to style. Common types include:
 Element selectors: (e.g., p, h1)
 ID selectors: (e.g., #myId)
 Class selectors: (e.g., .myClass)
 Attribute selectors: (e.g., [type="text"])
 Universal selector: (e.g., *)
 Descendant selectors: (e.g., div p)
 Child selectors: (e.g., div > p)
 Adjacent sibling selectors: (e.g., h2 + p)
 General sibling selectors: (e.g., h2 ~ p)
6. Explain the concept of CSS specificity. How is it calculated?
o Answer: Specificity determines which CSS rule will be applied to an element
when multiple rules conflict. It's calculated based on the types of selectors
used:
 Inline styles have the highest specificity.
 IDs are more specific than classes and pseudo-classes/elements.
 Classes, pseudo-classes, and attribute selectors have equal specificity.
 Element selectors and pseudo-elements have lower specificity.
 The universal selector and combinators have no specificity value. The
browser assigns a weight to each type of selector (often thought of as a,
b, c, d where a is inline, b is IDs, c is classes/attributes/pseudo-classes,
and d is elements/pseudo-elements) and compares them to determine
the most specific rule.
7. What is the cascade in CSS?
o Answer: The cascade refers to how CSS rules are applied when there are
multiple styles targeting the same element. It follows these principles (in order
of importance):
 Origin: Browser defaults, user styles, author styles (your CSS).
 Specificity: The more specific the selector, the higher its priority.
 Order: If specificity is the same, the last rule declared in the CSS will
take precedence.
8. What are pseudo-classes and pseudo-elements in CSS? Give some examples.
o Answer:
 Pseudo-classes: Select elements based on their state (e.g., :hover,
:active, :focus, :first-child, :last-child).
 Pseudo-elements: Select and style specific parts of an element (e.g.,
::before, ::after, ::first-letter, ::first-line).
9. Explain the difference between position: static, relative, absolute, fixed,
and sticky.
o Answer:
 static (default): Elements are positioned according to the normal
flow of the document. top, right, bottom, left, and z-index have
no effect.
 relative: Elements are positioned relative to their normal static
position. top, right, bottom, and left can be used to offset the
element without affecting the layout of other elements.
 absolute: Elements are positioned relative to the nearest positioned
ancestor (an ancestor with a position other than static). If there is
no positioned ancestor, it's positioned relative to the <html> element.
 fixed: Elements are positioned relative to the viewport and stay in the
same place even when the page is scrolled.
 sticky: Elements are initially positioned relative to their normal flow,
but they become fixed when they reach a certain scroll position
(specified by top, right, bottom, or left).
10. What is the float property in CSS? How can you clear floats?
o Answer: The float property is used to position an element to the left or right
of its container, allowing text and inline elements to wrap around it. Clearing
floats prevents subsequent elements from wrapping around the floated
element. Common methods include:
 Adding an empty <div> with clear: both; after the floated elements.
 Using the "clearfix" hack (applying a pseudo-element like ::after to
the parent container with properties like content: ""; display:
table; clear: both;).
11. What are flexbox and CSS Grid? When would you use each?
o Answer:
 Flexbox: A one-dimensional layout system that is excellent for
distributing space among items in a single row or column. Use it for
aligning items in a navigation bar, distributing space in a form, etc.
 CSS Grid: A two-dimensional layout system that allows you to
arrange elements in rows and columns. Use it for creating complex
page layouts with distinct regions.
12. How do you create responsive layouts using CSS?
o Answer: Techniques include:
 Fluid grids: Using percentage-based widths.
 Flexible images: Ensuring images scale with their containers (e.g.,
max-width: 100%).
 Media queries: Applying different styles based on screen size,
orientation, etc.
 Flexbox and Grid: These layout models are inherently responsive.
13. What are media queries? How are they used?
o Answer: Media queries allow you to apply different CSS styles based on the
characteristics of the device (e.g., screen width, height, orientation,
resolution). They are used with the @media rule in CSS. Example: @media
(max-width: 768px) { /* Styles for smaller screens */ }.
14. What is CSS preprocessor? Give some examples. What are their benefits?
o Answer: CSS preprocessors are scripting languages that extend the
capabilities of basic CSS, allowing you to use features like variables, mixins,
nesting, and functions, which are then compiled into standard CSS. Examples
include Sass, Less, and Stylus. Benefits include improved maintainability,
organization, and efficiency in writing CSS.
15. What are CSS variables (custom properties)? How are they used?
o Answer: CSS variables allow you to define reusable values within your CSS.
They are declared using a double hyphen ( --) followed by the variable name
and are accessed using the var() function. Example: --primary-color:
blue;. You can then use color: var(--primary-color);.
16. What are transitions and animations in CSS? How do you implement them?
o Answer:
 Transitions: Allow you to smoothly change CSS property values over
a specified duration when a property changes state (e.g., on hover).
Implemented using the transition property.
 Animations: Allow you to create more complex, keyframe-based
animations that can loop and have more control over the styling at
different points in time. Implemented using the @keyframes rule and
the animation property.
17. Explain the concept of CSS inheritance.
o Answer: Certain CSS properties are inherited by child elements from their
parent elements in the DOM tree (e.g., font-family, color, text-align).
Not all properties are inherited (e.g., border, padding, margin).
18. What is the z-index property? How does it work?
o Answer: The z-index property specifies the stack order of an element when it
overlaps with other elements. It only works on positioned elements
(position: relative, absolute, fixed, or sticky). Elements with a higher
z-index value will be stacked on top of elements with a lower value.
19. How do you optimize CSS for performance?
o Answer: Strategies include:
 Minifying CSS to reduce file size.
 Combining CSS files (though HTTP/2 makes this less critical).
 Using efficient selectors (avoid overly specific or complex selectors).
 Removing unused CSS.
 Using will-change to inform the browser of properties that are likely
to change.
20. What are some best practices for writing maintainable CSS?
o Answer: Best practices include:
 Using meaningful and consistent naming conventions for classes and
IDs.
 Keeping selectors specific enough but not overly complex.
 Organizing CSS into logical files or sections.
 Adding comments to explain the purpose of styles.
 Using a consistent formatting style.
 Avoiding overly long or deeply nested selectors.

JavaScript (20 Questions with Answers):

1. What is JavaScript?
o Answer: JavaScript is a high-level, interpreted, dynamically-typed
programming language primarily used to add interactivity to websites. It can
also be used for server-side development (Node.js), mobile app development
(React Native), and more.
2. Explain the difference between var, let, and const.
o Answer:
 var: Has function scope or global scope if declared outside a function.
Can be redeclared and reassigned. Hoisted to the top of its scope.
 let: Has block scope. Cannot be redeclared but can be reassigned.
Hoisted but not initialized.
 const: Has block scope. Cannot be redeclared or reassigned after
initialization. Hoisted but not initialized. Use const by default, then
let if reassignment is needed, and avoid var in modern JavaScript.
3. What are the different data types in JavaScript?
o Answer: Primitive data types: string, number, boolean, null, undefined,
symbol (ES6), bigint (ES2020).
o Object (reference) type: object (which includes arrays and functions).
4. What is the difference between == and === in JavaScript?
o Answer:
 == (Equality operator): Performs type coercion before comparison. For
example, "5" == 5 evaluates to true.
 === (Strict equality operator): Compares both the value and the data
type without type coercion. For example, "5" === 5 evaluates to
false. It's generally recommended to use === to avoid unexpected
behavior.
5. Explain the concept of scope in JavaScript. What are global, local, and block
scopes?
o Answer: Scope determines the accessibility of variables.
 Global scope: Variables declared outside any function or block have
global scope and are accessible throughout the entire script.
 Local (function) scope: Variables declared inside a function are only
accessible within that function.
 Block scope: Variables declared with let or const inside a block
(e.g., if statement, for loop) are only accessible within that block. var
does not have block scope.
6. What are closures in JavaScript? How are they useful?
o Answer: A closure is a feature in JavaScript where an inner function has
access to the outer (enclosing) function's variables — even after the outer
function has finished executing. This happens because the inner function
"closes over" the environment of the outer function. Closures are useful for:
 Data encapsulation and privacy.
 Creating function factories.
 Maintaining state in asynchronous operations.
7. What is the this keyword in JavaScript? How does its value change?
o Answer: The this keyword refers to the object that is currently executing the
code. Its value depends on how the function is called:
 Global context: In non-strict mode, this refers to the global object
(window in browsers). In strict mode, it's undefined.
 Function invocation: If a function is called directly, this refers to the
global object (or undefined in strict mode).
 Method invocation: When a function is called as a method of an
object, this refers to that object.
 Constructor invocation: When a function is called with the new
keyword, this refers to the newly created object.
 call(), apply(), and bind(): These methods allow you to explicitly
set the value of this.
8. Explain the concepts of call, apply, and bind in JavaScript.
o Answer: These are methods that allow you to manipulate the this context of
a function:
 call(): Invokes the function with a specified this value and
arguments provided individually. function.call(thisArg, arg1,
arg2, ...)
 apply(): Invokes the function with a specified this value and
arguments provided as an array (or an array-like object).
function.apply(thisArg, [argsArray])
 bind(): Creates a new function (a bound function) with the this value
and optionally some of the arguments already specified. The bound
function is not immediately invoked. const boundFunction =
function.bind(thisArg, arg1, ...)
9. What are higher-order functions in JavaScript? Give some examples.
o Answer: Higher-order functions are functions that operate on other functions,
either by taking them as arguments or by returning them. Examples include:
 map(): Transforms each element in an array using a provided function.
 filter(): Creates a new array with elements that pass a test
implemented by a provided function.
 reduce(): Applies a function against an accumulator and each element
of the array to reduce it to a single value.
 forEach(): Executes a provided function once for each array element.
 Functions returned by other functions (closures are often used here).
10. Explain the difference between synchronous and asynchronous JavaScript.
o Answer:
 Synchronous: Code executes line by line, in order. Each operation
must complete before the next one can start. This can lead to blocking
if an operation takes a long time.
 Asynchronous: Code allows multiple operations to run concurrently
without blocking the main thread. When an asynchronous operation
completes, a callback function or a promise is used to handle the result.
This is essential for handling I/O operations (like network requests)
efficiently.
11. How do you handle asynchronous operations in JavaScript? Explain callbacks,
Promises, and async/await.
o Answer:
 Callbacks: Functions passed as arguments to other functions (often
asynchronous ones). They are executed when the asynchronous
operation completes. Can lead to "callback hell" (nested callbacks) for
complex asynchronous flows.
 Promises: Objects that represent the eventual completion (or failure)
of an asynchronous operation and its resulting value. A promise can be
in one of three states: pending, fulfilled (with a value), or rejected
(with a reason). They provide a cleaner way to handle asynchronous
code using .then() (for success) and .catch() (for errors).
 async/await: Syntax sugar built on top of Promises (ES2017). async
declares an asynchronous function that implicitly returns a promise.
await pauses the execution of an async function until a promise is
resolved or rejected. Makes asynchronous code look and behave more
like synchronous code, improving readability.
12. What are event listeners in JavaScript? How do you add and remove them?
o Answer: Event listeners are used to detect and respond to events that occur in
the browser (e.g., clicks, mouseovers, key presses). You can add event
listeners using:
 element.addEventListener(type, listener[, options]);
 Inline HTML attributes (less recommended): <button
onclick="myFunction()">Click Me</button> You can remove
event listeners using:
 element.removeEventListener(type, listener[, options]);
(Note: You need to pass the exact same listener function that was
originally added).
13. What is DOM manipulation? How do you select and modify elements in the
DOM?
o Answer: DOM (Document Object Model) manipulation refers to the ability of
JavaScript to dynamically access and modify the structure, style, and content
of an HTML document. You can select elements using methods like:
 document.getElementById('myId')
 document.querySelector('.myClass') (returns the first matching
element)
 document.querySelectorAll('.myClass') (returns a NodeList of
all matching elements)
 document.getElementsByTagName('p') You can modify elements
using properties and methods like:
 element.innerHTML = 'New content';
 element.textContent = 'New text';
 element.style.color = 'red';
 element.classList.add('new-class');
 element.appendChild(newNode);
 element.removeChild(childNode);
14. What is event bubbling and event capturing in JavaScript?
o Answer: These are two ways that event propagation occurs in the DOM when
an event happens on an element that is nested within other elements.
 Event Bubbling (default): The event first triggers on the innermost
target element, and then propagates (bubbles up) through its ancestors
in the DOM tree until it reaches the document object.
 Event Capturing: The event first triggers on the outermost ancestor
element (usually the window or document), and then propagates down
to the target element. You can use capturing by passing true as the
third argument to addEventListener:
element.addEventListener(type, listener, true);.
15. What are prototypes in JavaScript? How does prototype inheritance work?
o Answer: Every JavaScript object has an associated prototype object. When
you try to access a property of an object, and the object itself doesn't have that
property, JavaScript will look for the property in the object's prototype, then in
the prototype's prototype, and so on, up the prototype chain until it finds the
property or reaches the end of the chain (which is null). This mechanism is
called prototype inheritance. It allows objects to inherit properties and
methods from their prototypes.
16. Explain the concept of classes in JavaScript. How are they related to prototypes?
o Answer: ES6 (ECMAScript 2015) introduced class syntax to JavaScript,
providing a more familiar way to create objects using a class-based approach
similar to other object-oriented languages. However, JavaScript classes are
syntactic sugar over prototype-based inheritance. When you define a class,
you are essentially creating a constructor function and defining methods on its
prototype. The class syntax makes it easier to define and organize object
creation and inheritance patterns.
17. What are modules in JavaScript? How do you use import and export?
o Answer: Modules are a way to organize JavaScript code into reusable pieces.
They help to avoid naming conflicts and improve code maintainability.
Modern JavaScript uses ES modules, which are supported natively in browsers
and Node.js.
 export: Used to make variables, functions, classes, etc., available to
other modules. You can have named exports (e.g., export const
myVariable = 10;) or a single default export (e.g., export default
myFunction;).
 import: Used to bring in functionality from other modules. You can
import named exports (e.g., import { myVariable } from
'./myModule.js';) or the default export (e.g., import myFunction
from './myModule.js';).
18. What is the difference between null and undefined in JavaScript?
o Answer: Both represent the absence of a value, but they have slightly
different meanings:
 null: An assignment value. It represents the intentional absence of an
object value. You explicitly set a variable to null to indicate that it
should have no value. typeof null returns "object" (a known
historical bug).
 undefined: Indicates that a variable has not been assigned a value, or
a function does not explicitly return a value. It can also be the value of
a property that does not exist in an object. typeof undefined returns
"undefined".
19. What are some common JavaScript libraries and frameworks?
o Answer: Common libraries include jQuery (though less used in modern
development), Lodash, Moment.js (or Date-fns). Popular frameworks include
React, Angular, and Vue.js. Node.js is a popular runtime environment for
server-side JavaScript.
20. How do you debug JavaScript code? What tools can you use?
o Answer: Common debugging techniques include:
 console.log(): Logging values and messages to the browser's
developer console.
 debugger statement: Inserting breakpoints in your code to pause
execution in the browser's debugger.
 Browser Developer Tools (Inspect Element): Providing features like
a debugger, console, network monitoring, and element inspection.
 Error messages: Carefully reading and understanding error messages
in the console.
 Code editors with debugging features: Many editors (like VS Code)
have built-in debuggers that allow you to step through your code,
inspect variables, and set breakpoints.

React (20 Questions with Answers):

1. What is React? What are its key features and benefits?


o Answer: React is a JavaScript library for building user interfaces or UI
components. Key features and benefits include:
 Component-based architecture: UIs are broken down into reusable
and independent components.
 Virtual DOM: React uses a virtual DOM, which is a lightweight in-
memory representation of the real DOM. It efficiently updates the
actual DOM by only re-rendering changed components.
 JSX: A syntax extension that allows you to write HTML-like code
within JavaScript.
 Declarative programming: You describe what the UI should look
like based on the state, and React handles the DOM updates.
 One-way data binding: Data flows in one direction (typically from
parent to child), making it easier to manage and track changes.
 Large and active community: Extensive documentation, resources,
and third-party libraries available.
 Cross-platform development (with React Native): Allows building
mobile apps using JavaScript and React concepts.
2. Explain the concept of JSX. Why do we use it?
o Answer: JSX (JavaScript XML) is a syntax extension for JavaScript that
allows you to write HTML-like code directly within your JavaScript files. It
gets transformed into regular JavaScript function calls that create React
elements. We use JSX because it makes it more intuitive and easier to describe
the structure of the UI components, especially for those familiar with HTML.
It improves readability and developer experience.
3. What are components in React? Differentiate between functional and class
components.
o Answer: Components are the building blocks of a React application. They are
reusable and independent pieces of UI.
 Functional components: Simple JavaScript functions that accept
props as arguments and return JSX. They are generally used for
presentational logic and stateless components. (e.g., const
MyComponent = (props) => { return <h1>{props.name}</h1>;
};)
 Class components: JavaScript classes that extend React.Component.
They can have state, lifecycle methods, and are typically used for more
complex logic and stateful components. (e.g., class MyComponent
extends React.Component { constructor(props) {
super(props); this.state = { count: 0 }; } render() {
return <div>Count: {this.state.count}</div>; } }) With the
introduction of Hooks in React 16.8, functional components can now
also manage state and have lifecycle-like behavior, making them the
preferred choice for most component implementations.
4. What are props in React? How are they passed and used?
o Answer: Props (short for "properties") are used to pass data from a parent
component to a child component. They are read-only from the perspective of
the child component. Props are passed down as attributes to the child
component when it is rendered in the parent. Inside the child component,
props are accessed as properties of the props object (for functional
components) or this.props (for class components). (e.g., In parent:
<ChildComponent message="Hello from parent" />. In child: const
ChildComponent = (props) => { return <p>{props.message}</p>;
};)
5. What is state in React? How is it different from props?
o Answer: State is used to manage data that can change over time within a
component. It is internal to the component and controls its behavior and
rendering.
 State: Mutable, managed within the component, can be changed using
setState (for class components) or the state updater function returned
by useState Hook (for functional components). Changes to state
trigger re-renders of the component and its descendants.
 Props: Immutable from the child's perspective, passed down from
parent components. Child components can receive data through props
but should not directly modify them. Props are used to communicate
data from parent to child.
6. Explain the React component lifecycle methods (for class components).
o Answer: Lifecycle methods are special methods that are invoked at different
stages of a component's existence. Common ones include:
 constructor(props): Called when the component is being created.
Used for initializing state, binding event handlers.
 render(): Required method. Returns the JSX to be rendered. Should
be a pure function of props and state.
 componentDidMount(): Called after the component has been rendered
to the DOM. Good place for fetching data, setting up subscriptions.
 componentDidUpdate(prevProps, prevState, snapshot): Called
after the component's props or state have been updated. Good for
performing side effects based on changes.
 componentWillUnmount(): Called just before the component is
removed from the DOM. Used for cleanup (e.g., removing event
listeners, canceling subscriptions).
 (Less common) shouldComponentUpdate(nextProps, nextState):
Determines if the component should re-render. Can be used for
performance optimization.
 (Less common) static getDerivedStateFromProps(nextProps,
prevState): Called before render. Allows updating state based on
changes in props.
 (Less common) getSnapshotBeforeUpdate(prevProps,
prevState): Called right before the most recent rendering. Can
capture information from the DOM before it's potentially changed.
7. What are React Hooks? List some common built-in Hooks and explain their use.
o Answer: Hooks are functions that let you "hook into" React state and lifecycle
features from functional components. They were introduced in React 16.8 and
provide a way to use state and other React features without writing classes.
Common built-in Hooks include:
 useState(initialState): Allows functional components to have
state. Returns a state variable and a function to update it.
 useEffect(effect, [dependencies]): Performs side effects in
functional components (similar to componentDidMount,
componentDidUpdate, and componentWillUnmount combined). The
effect runs after every render unless the dependencies array is
provided. If the dependencies array is empty ([]), the effect runs only
once after the initial render and cleans up when the component
unmounts.
 useContext(Context): Allows functional components to access data
from a React Context.
 useRef(initialValue): Returns a mutable ref object whose
.current property is initialized to the argument ( initialValue). Can
be used to access DOM elements or hold mutable values that don't
trigger re-renders.
 useCallback(callback, [dependencies]): Returns a memoized
callback function. Useful for preventing unnecessary re-renders of
child components that rely on this callback.
 useMemo(create, [dependencies]): Returns a memoized value.
Useful for expensive calculations that should only be re-run if the
dependencies have changed.
 useReducer(reducer, initialState): An alternative to useState
for more complex state logic. Returns the current state and a dispatch
function to update it based on a reducer function.
8. How do you handle events in React?
o Answer: React handles events similarly to native DOM elements but with
some differences:
 Event handlers are written in camelCase (e.g., onClick instead of
onclick).
 Event handlers are passed as functions to the element.
 React uses synthetic events, which are wrapper objects around the
browser's native event objects. They have the same interface as native
events but work consistently across different browsers.
 You can prevent default behavior using event.preventDefault().
 You can stop event propagation using event.stopPropagation().
9. What is conditional rendering in React? Explain different approaches.
o Answer: Conditional rendering means displaying different UI elements based
on certain conditions. Common approaches include:
 if statements: Using regular JavaScript if/else or ternary operators
within the render method (or within the JSX in functional
components).
 Ternary operator (condition ? <ComponentA /> : <ComponentB
/>): A concise way to render one of two different components or
values.
 Logical AND operator (condition && <ComponentA />): If the
condition is true, ComponentA will be rendered; otherwise, nothing will
be rendered.
 Creating separate components for different states: Render different
components based on the current state or props.
10. How do you handle lists and keys in React? Why are keys important?
o Answer: To render lists of items in React, you typically use the map()
function on an array to transform each item into a React element. Each
element in the list should have a unique key prop. Keys help React identify
which items have changed, been added, or been removed. This is crucial for
efficiently updating the DOM, especially when dealing with dynamic lists or
animations. Without unique keys, React might re-render all the list items
unnecessarily.
11. What is component composition in React?
o Answer: Component composition is a pattern in React where you create
complex UIs by combining smaller, simpler components. Instead of relying
heavily on inheritance, you pass data and children down through the
component tree using props. This leads to more flexible and reusable
components. Common patterns include passing props that render children or
using the children prop to render content passed between the opening and
closing tags of a component.
12. What is controlled and uncontrolled components in React?
o Answer: In the context of form elements:
 Controlled components: Form elements whose values are controlled
by React state. When the user types in the input, an event handler
updates the state, and the component re-renders with the new value.
This gives React full control over the form data.
 Uncontrolled components: Form elements whose values are managed
by the DOM itself. You can access their values using refs. While
simpler to implement initially, they make it harder to implement
complex validation or conditional logic based on the form data.
Controlled components are generally preferred for better control and
predictability.
13. How do you handle form submissions in React?
o Answer: Typically involves:
 Using a <form> element.
 Attaching an onSubmit event handler to the <form>.
 Within the handler, prevent the default form submission behavior using
event.preventDefault().
 Access the form data (either from the component's state in controlled
components or using refs in uncontrolled components).
 Perform any necessary validation and then make an API call or process
the data.
14. What is the purpose of the React Router library? How do you implement
routing?
o Answer: React Router is a popular third-party library used for implementing
navigation and routing in React applications (especially for Single-Page
Applications - SPAs). It allows you to define different "pages" or views within
your application and navigate between them without requiring a full page
reload from the server. Implementation involves:
 Installing the react-router-dom package.
 Using components like <BrowserRouter> (wraps your app), <Route>
(defines a mapping between a path and a component), <Link> or
<NavLink> (for creating links that trigger navigation).
 Using Switch (to render the first matching route) and Redirect (to
navigate to a different route).
15. What is state management in React? Explain different approaches and libraries
(e.g., Context API, Redux, Zustand).
o Answer: State management in React deals with how to handle and share data
across multiple components, especially in larger applications where prop
drilling (passing props down many levels) can become cumbersome. Different
approaches and libraries include:
 Component state (useState, useReducer): Suitable for local
component-specific state.
 Prop drilling: Passing state down through the component tree via
props. Can become difficult to manage in deep trees.
 Context API: Built-in React feature that allows you to share data
across the component tree without explicitly passing props at every
level. Useful for theming, user authentication status, etc.
 Redux: A popular predictable state container library. It uses a single
global store, actions to describe changes, and reducers to update the
store based on actions. Provides a structured approach to managing
complex state.
 Zustand: A smaller and simpler state management library that uses a
central store with a focus on ease of use.
 Recoil: An experimental state management library from Facebook that
provides a more granular and flexible approach compared to Redux.
 MobX: Another popular state management library that uses observable
data and reactions to manage state.
16. What is the Context API in React? When would you use it?
o Answer: The 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
sharing values that are considered "global" for a tree of React components,
such as the current authenticated user, theme, or preferred language. You
create a Context object using React.createContext(), then provide a value
to the consuming components using a Context.Provider and access the
value in child components using Context.Consumer (or the useContext
Hook in functional components).
17. What is Redux? Explain its core principles (store, actions, reducers).
o Answer: Redux is a predictable state container for JavaScript applications. Its
core principles are:
 Single source of truth (Store): The entire state of the application is
stored in a single object called the "store." This makes it easier to
understand and manage the application's state.
 State is read-only (Actions): The only way to change the state is to
dispatch an "action," which is a plain JavaScript object describing what
happened. Actions are the only way to interact with the store and
trigger state changes.
 Changes are made with pure functions (Reducers): Reducers are
pure functions that take the current state and an action as arguments
and return the new state. They must be pure, meaning they should not
have side effects and should always return the same output for the
same input.
18. How do you make API calls in React?
o Answer: You can use standard JavaScript methods like fetch or libraries like
Axios to make HTTP requests to APIs. Typically, you would perform API
calls within lifecycle methods (like componentDidMount in class components)
or using the useEffect Hook in functional components. You'll need to handle
the loading state, fetch the data, and update the component's state with the
retrieved data. Error handling (using .catch() with Promises or try/catch
with async/await) is also important.
19. What are some best practices for optimizing React application performance?
o Answer:
 Using React.memo for functional components and
shouldComponentUpdate for class components to prevent
unnecessary re-renders.
 Memoizing expensive computations with useMemo and callbacks
with useCallback.
 Lazy loading components with React.lazy and Suspense to
improve initial load time.
 Code splitting to break down your application into smaller bundles
that are loaded on demand.
 Avoiding unnecessary state updates.
 Using efficient data structures.
 Debouncing and throttling event handlers for performance-sensitive
interactions.
 Virtualization for large lists (e.g., react-virtualized, react-
window).
20. How do you test React applications? What testing libraries can you use (e.g.,
Jest, React Testing Library)?
o Answer: Testing is crucial for ensuring the quality and reliability of React
applications. Common testing approaches include:
 Unit testing: Testing individual components or functions in isolation.
Jest is a popular JavaScript testing framework often used with React
for unit tests.
 Integration testing: Testing how different parts of the application
work together (e.g., how components interact). React Testing Library
is a great choice for integration tests as it focuses on testing the user's
perspective by interacting with the rendered output.
 End-to-end (E2E) testing: Testing the entire application flow from
the user's perspective (often using tools like Cypress or Selenium).
React Testing Library encourages testing based on what users see and
interact with rather than relying on implementation details. It provides
utilities for rendering components, finding elements, and simulating
user interactions. Jest is used for writing test cases, making assertions,
and providing mocking capabilities.

You might also like