Lecture Notes Of Day 24: Component Design and Composition
Objective:
To learn the principles
of designing and composing reusable components in modern web development.
Outcome:
By the end of this
lecture, students will be able to:
Build modular,
reusable, and testable components.
Follow best practices
for component design and composition.
Introduction to
Components
A component is a
building block in modern web development frameworks (e.g., React, Vue,
Angular). Components:
Represent small,
reusable pieces of the user interface (UI).
Allow developers to
break down a complex UI into manageable chunks.
Can be customized using
props (properties).
Example: In a web app,
a Button or Navbar can be a component.
Why Use Components?
Reusability: Write
once, use in multiple places.
Modularity: Makes the application
easier to manage and debug.
Maintainability:
Isolate functionality in separate components for better code organization.
Scalability: Easily add
new features by composing existing components.
Principles of Component
Design
Single Responsibility
Principle (SRP):
Each component should
have one clear responsibility.
Example: A Header
component should only handle the header UI, not business logic.
Reusability:
Design components that
can be reused with different data or contexts.
Use props to make
components dynamic.
Avoid hardcoding values
inside components.
Example: A Button
component can have different labels like "Submit" or
"Cancel" using props.
Encapsulation:
Hide the implementation
details of a component.
The internal state or
behavior should not directly affect other components.
Separation of Concerns:
Keep UI, logic, and
styles separate.
Use tools like
CSS-in-JS or style modules for styling.
Composition over
Inheritance:
Combine smaller
components into larger ones instead of inheriting behavior.
Example: Build a Form
component by composing Input and Button components.
Key Concepts in
Component Composition
Props
Mechanism to pass data
to components.
Example:
javascript
Copy code
function
Greeting(props) {
return <h1>Hello,
{props.name}!</h1>;
}
<Greeting
name="Alice" /> // Output:
Hello, Alice!
Children Prop
Allows components to
wrap other components or elements.
Example:
javascript
Copy code
function Card(props) {
return <div
className="card">{props.children}</div>;
}
<Card>
<h2>Title</h2>
<p>Content inside the card.</p>
</Card>
State
Tracks data that
changes over time within a component.
Example in React:
javascript
Copy code
import { useState }
from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() =>
setCount(count + 1)}>Increment</button>
</div>
);
}
Lifecycle Methods or
Effects
Handle events like
mounting, updating, or unmounting of components.
Example in React:
javascript
Copy code
import { useEffect }
from 'react';
function DataFetcher()
{
useEffect(() => {
console.log('Component mounted or
updated');
}, []);
return <div>Fetching
data...</div>;
}
Higher-Order Components
(HOCs)
A function that takes a
component and returns a new component with added functionality.
Example: Logging
component props.
javascript
Copy code
function
withLogger(WrappedComponent) {
return function Enhanced(props) {
console.log(props);
return <WrappedComponent {...props}
/>;
};
}
Best Practices for
Component Design
Keep Components Small
and Focused
A component should do
one thing well.
Avoid Too Many Props
Use only the props
needed for functionality.
Use Default Props and
Prop Validation
Default props provide
fallback values.
Prop validation ensures
the correctness of passed data.
javascript
Copy code
Greeting.defaultProps =
{
name: 'Guest',
};
Greeting.propTypes = {
name: PropTypes.string.isRequired,
};
Use Meaningful Names
Components should have
names that reflect their purpose.
Separate Logic and
Presentation
Use presentational
components for UI and container components for logic.
Activity: Building
Reusable Components
Create a Button
component with customizable:
Text
Color
OnClick handler
Example Code:
javascript
Copy code
function Button({ text,
color, onClick }) {
return (
<button style={{ backgroundColor: color
}} onClick={onClick}>
{text}
</button>
);
}
<Button
text="Click Me" color="blue" onClick={() =>
alert('Clicked!')} />;
Build a Card component
to display content:
Accepts title and
content as props.
Uses children to allow
flexible content.
Example Code:
javascript
Copy code
function Card({ title,
children }) {
return (
<div className="card">
<h3>{title}</h3>
{children}
</div>
);
}
<Card
title="Welcome">
<p>This is the card content.</p>
</Card>;
Summary
Components make
development modular, reusable, and maintainable.
Follow principles like
SRP, reusability, and encapsulation.
Use props, state, and
composition to create flexible and robust components.
Best practices ensure
the design remains scalable and testable.
Assignment
Create a TodoItem
component that accepts a task and a completed status.
Create a TodoList
component that displays a list of TodoItems.
Implement state
management to toggle the completion status of tasks.
You said:
WRITE SOME ASSIGNMENTS
FROM ABOVE CONCEPT WITH STEP BY STEP SOLUTIONS with explanation
ChatGPT said:
ChatGPT
Assignments with
Step-by-Step Solutions
Assignment 1: Create a
Button Component
Problem Statement:
Create a reusable
Button component with the following features:
Accepts text (button
label), color (background color), and onClick (function to handle click events)
as props.
Render the button with
customizable styles.
Step-by-Step Solution:
Step 1: Create the
Button Component
Start with a functional
component in React.
Accept props (text,
color, and onClick) as arguments.
Use the style attribute
to apply dynamic background color.
Use the onClick prop
for handling click events.
Code:
javascript
Copy code
function Button({ text,
color, onClick }) {
return (
<button style={{ backgroundColor: color
}} onClick={onClick}>
{text}
</button>
);
}
Step 2: Use the Button
Component in an Application
Import the Button
component.
Pass the required props
(text, color, onClick).
Add an alert or
console.log to handle click events.
Code:
javascript
Copy code
import React from
'react';
import ReactDOM from
'react-dom';
import Button from
'./Button';
function App() {
const handleClick = () => {
alert('Button clicked!');
};
return (
<div>
<Button text="Click Me"
color="blue" onClick={handleClick} />
<Button text="Delete"
color="red" onClick={() => console.log('Deleted')} />
</div>
);
}
ReactDOM.render(<App
/>, document.getElementById('root'));
Explanation:
The Button component is
fully reusable.
You can pass different
labels (text) and colors to change the appearance.
The onClick function
adds dynamic functionality.
Assignment 2: Create a
Card Component
Problem Statement:
Create a Card component
that:
Accepts a title (as a
prop).
Renders any content
(using props.children).
Styles the card with a
border and padding.
Step-by-Step Solution:
Step 1: Create the Card
Component
Define a functional
component.
Use props.title to display
the card title.
Render props.children
for flexible content.
Apply inline styles for
a border and padding.
Code:
javascript
Copy code
function Card({ title,
children }) {
return (
<div style={{ border: '1px solid #ccc',
padding: '20px', borderRadius: '5px' }}>
<h3>{title}</h3>
{children}
</div>
);
}
Step 2: Use the Card
Component in an Application
Import the Card
component.
Pass a title as a prop.
Add content inside the
component using JSX.
Code:
javascript
Copy code
import React from
'react';
import ReactDOM from
'react-dom';
import Card from
'./Card';
function App() {
return (
<div>
<Card title="Card 1">
<p>This is the content for Card
1.</p>
</Card>
<Card title="Card 2">
<button>Click Me</button>
</Card>
</div>
);
}
ReactDOM.render(<App
/>, document.getElementById('root'));
Explanation:
The Card component uses
props.children to allow custom content inside the card.
The title is rendered
dynamically, making the component reusable.
Inline styles ensure
the card looks consistent.
Assignment 3: Create a
TodoList Component
Problem Statement:
Build a TodoList
application that:
Displays a list of
tasks using a TodoItem component.
Toggles the completion
status of tasks.
Step-by-Step Solution:
Step 1: Create the
TodoItem Component
Accept task and
completed props.
Style the task as
"crossed out" if completed.
Add a button to toggle
the status.
Code:
javascript
Copy code
function TodoItem({
task, completed, toggleStatus }) {
return (
<div>
<p style={{ textDecoration: completed
? 'line-through' : 'none' }}>{task}</p>
<button
onClick={toggleStatus}>{completed ? 'Undo' : 'Complete'}</button>
</div>
);
}
Step 2: Create the
TodoList Component
Use useState to manage
the list of tasks and their status.
Pass task data and
toggle functionality to TodoItem components.
Code:
javascript
Copy code
import React, {
useState } from 'react';
import TodoItem from
'./TodoItem';
function TodoList() {
const [todos, setTodos] = useState([
{ id: 1, task: 'Learn React', completed:
false },
{ id: 2, task: 'Build a Project',
completed: false },
]);
const toggleStatus = (id) => {
setTodos((prevTodos) =>
prevTodos.map((todo) =>
todo.id === id ? { ...todo, completed:
!todo.completed } : todo
)
);
};
return (
<div>
{todos.map((todo) => (
<TodoItem
key={todo.id}
task={todo.task}
completed={todo.completed}
toggleStatus={() =>
toggleStatus(todo.id)}
/>
))}
</div>
);
}
export default
TodoList;
Step 3: Render the
TodoList Component
Import and render
TodoList in your app.
Code:
javascript
Copy code
import React from
'react';
import ReactDOM from
'react-dom';
import TodoList from
'./TodoList';
function App() {
return (
<div>
<h1>Todo List</h1>
<TodoList />
</div>
);
}
ReactDOM.render(<App
/>, document.getElementById('root'));
Explanation:
The TodoList component
manages the list of tasks.
The TodoItem component
displays individual tasks and their statuses.
useState allows dynamic
updates to the task list.
Summary of Assignments:
Button Component:
Demonstrates how to create reusable UI elements with dynamic behavior.
Card Component:
Introduces props.children for flexible content.
TodoList Application:
Combines state management and composition for real-world use cases.
By completing these
assignments, students practice designing, composing, and managing reusable
components.
2/2
You said:
WRITE 100 no of MCQs
only FROM ABOVE CONCEPT with explanation
ChatGPT said:
ChatGPT
Here are 100 MCQs based
on the concept of "Component Design and Composition" with
explanations. These MCQs are organized into sections for clarity.
Basics of Components
What is a React
component?
A. A function or class
that outputs JSX
B. A method to style
elements
C. A variable storing
data
D. A JavaScript library
for testing
Answer: A
Explanation: Components
in React are functions or classes that return JSX, defining the UI structure.
What is the main
advantage of reusable components?
A. Faster loading times
B. Reduces repetitive
code
C. Provides additional
features
D. Improves server-side
rendering
Answer: B
Explanation: Reusable
components help avoid duplication, making the codebase easier to maintain.
What is the standard
way to define a functional component?
A. Using function keyword
B. Using class keyword
C. Using const with
arrow functions
D. Both A and C
Answer: D
Explanation: Functional
components can be created using the function keyword or arrow functions.
Which of the following
is NOT a type of component in React?
A. Functional
B. Class-based
C. Stateful
D. Server-side
Answer: D
Explanation: Components
in React are either functional or class-based. Server-side is unrelated to
React components.
What does props stand
for?
A. Properties
B. Prototypes
C. Propagation
D. Processes
Answer: A
Explanation: props
stands for properties, allowing components to receive data.
Props
What is props.children
used for?
A. To pass a child
component
B. To render nested
elements
C. To validate prop
types
D. To handle lifecycle
methods
Answer: B
Explanation:
props.children represents nested elements inside a component.
How are props passed to
components?
A. Using a state
variable
B. As arguments during
function calls
C. Using attributes in
JSX
D. Automatically
inherited
Answer: C
Explanation: Props are
passed using attributes when the component is rendered in JSX.
Can props be mutated
inside a component?
A. Yes
B. No
Answer: B
Explanation: Props are
read-only and cannot be changed inside the component.
Which is true about
props in React?
A. They are immutable
B. They are used for
passing data
C. They can be any data
type
D. All of the above
Answer: D
Explanation: Props are
immutable, used for passing data, and support multiple types (strings, numbers,
objects, etc.).
What happens if a
required prop is missing?
A. An error is thrown
B. The app crashes
C. A default value is
used if defined
D. It is silently
ignored
Answer: C
Explanation: Missing
required props can cause issues unless default values are set using defaultProps.
State
What is the difference
between props and state?
A. Props are for input,
state is for output
B. Props are immutable,
state is mutable
C. Props are mutable,
state is immutable
D. Props manage UI,
state manages data
Answer: B
Explanation: Props are
immutable and used for passing data, while the state is mutable and manages
component data.
Which React hook is
used to manage state?
A. useEffect
B. useReducer
C. useState
D. useMemo
Answer: C
Explanation: The
useState hook is specifically for managing state in functional components.
Component Composition
What does composition
in React mean?
A. Combining components
to form complex UIs
B. Overloading
functions in components
C. Passing methods as
props
D. Styling components
dynamically
Answer: A
Explanation:
Composition refers to combining components to build reusable and scalable UIs.
Which technique is an
example of composition?
A. Conditional
rendering
B. Nesting components
C. Using event handlers
D. Declaring variables
Answer: B
Explanation: Nesting
components is a way to compose multiple smaller components into a complex UI.
What is the main
benefit of composition?
A. Code duplication
B. Improved testability
and modularity
C. Increased code size
D. Enhanced performance
Answer: B
Explanation:
Composition ensures modularity and makes testing individual components easier.
Practical Use Cases
Which prop would you
use to pass a click handler function to a button component?
A. text
B. onClick
C. handleClick
D. clickEvent
Answer: B
Explanation: The
onClick prop is conventionally used for handling click events.
What is a higher-order
component (HOC)?
A. A component that
renders another component
B. A built-in React
hook
C. A way to manage
state
D. A CSS styling method
Answer: A
Explanation: HOCs wrap
other components to enhance their functionality.
Advanced Concepts
What are controlled
components?
A. Components with
dynamic content
B. Components with
state managed by React
C. Components directly
modifying DOM
D. Components used for
error handling
Answer: B
Explanation: Controlled
components rely on React state for managing input values.
What is the role of key
in lists?
A. To provide unique
IDs for efficient updates
B. To identify props
C. To track changes in
state
D. To debug components
Answer: A
Explanation: Keys help
React efficiently identify and update individual list items.
What happens if a key
is not unique in a list?
A. React will throw an
error
B. The app will crash
C. Rendering bugs may
occur
D. Nothing will happen
Answer: C
Explanation: Duplicate
keys can cause rendering issues since React relies on them for reconciliation.
The remaining 80
questions can be developed in a similar format, covering state, hooks, event
handling, advanced composition techniques, real-world examples, and best
practices. Each question can focus on specific scenarios, methods, and concepts
from "Component Design and Composition." If you'd like, I can create
more of these questions! Let me know.
You said:
yes
ChatGPT said:
ChatGPT
Here’s a continuation
with more MCQs focusing on state management, hooks, event handling, advanced
composition techniques, real-world examples, and best practices:
State Management
When should you use
useReducer instead of useState?
A. When managing simple
states
B. For performance
optimization
C. For complex state
logic
D. To reduce the size
of the component
Answer: C
Explanation: useReducer
is ideal for handling complex state transitions, especially with multiple
actions.
What does the setState
function do in React?
A. Directly mutates the
state
B. Schedules a
re-render with updated state
C. Immediately updates
the UI
D. Resets the
component's state
Answer: B
Explanation: setState
schedules a state update, triggering a re-render when the state changes.
What is the default
value of a useState hook?
A. Null
B. Undefined
C. The initial value
provided
D. An empty object
Answer: C
Explanation: useState
initializes the state with the value provided as an argument.
How can you share state
between two sibling components?
A. Using props
B. Using context
C. Lifting state up to
a common parent
D. Both B and C
Answer: D
Explanation: State can
be shared between siblings by lifting it to a common parent or using React
Context.
What happens when you
call setState with the same value as the current state?
A. React triggers a
re-render
B. Nothing happens
C. The app crashes
D. React throws an
error
Answer: B
Explanation: React
optimizes rendering by skipping updates if the new state is the same as the
current state.
Hooks
Which of the following
is NOT a built-in React hook?
A. useState
B. useEffect
C. useData
D. useMemo
Answer: C
Explanation: useData is
not a built-in React hook.
What does the useEffect
hook do?
A. Manages component
state
B. Runs side effects in
components
C. Optimizes
performance
D. Updates the DOM
Answer: B
Explanation: useEffect
is used to handle side effects such as data fetching or subscriptions.
When does the cleanup
function in useEffect run?
A. On every render
B. On component unmount
or before the effect re-runs
C. Only on unmount
D. After the state
changes
Answer: B
Explanation: The
cleanup function runs before the next effect or when the component unmounts.
How can you prevent an
infinite loop with useEffect?
A. Use conditional
logic in the effect
B. Add a dependency
array
C. Avoid setting state
inside the effect
D. All of the above
Answer: D
Explanation: Adding a
dependency array and careful coding inside useEffect avoids infinite loops.
What does useMemo do in
React?
A. Stores data
persistently
B. Caches expensive
calculations
C. Creates a new state
variable
D. Updates the
component's state
Answer: B
Explanation: useMemo
memoizes expensive calculations to improve performance.
Event Handling
How do you bind an
event handler in a functional component?
A. Using bind(this)
B. Directly inside JSX
C. Using useEffect
D. Using context
Answer: B
Explanation: In
functional components, event handlers can be directly passed as inline
functions or methods in JSX.
What is the difference
between onClick={this.handleClick} and onClick={this.handleClick()}?
A. One binds the
function, and the other calls it immediately
B. Both are the same
C. One uses arrow
functions
D. One is for props,
and the other is for state
Answer: A
Explanation:
onClick={this.handleClick} passes the reference, while onClick={this.handleClick()}
calls the function immediately.
What event property is
used to prevent the default browser behavior?
A. preventDefault
B. stopPropagation
C. cancelEvent
D. stopDefault
Answer: A
Explanation:
event.preventDefault() is used to stop the default behavior, like preventing
form submission.
How do you pass
parameters to an event handler?
A. Using arrow
functions
B. By directly calling
the function
C. By using a callback
wrapper
D. Both A and C
Answer: D
Explanation: Arrow
functions or callback wrappers are commonly used to pass parameters in event
handlers.
Advanced Composition
Techniques
What is the difference
between children and props in React?
A. children is a
default prop for nesting, while other props are explicitly passed
B. children are dynamic
props
C. Props are mutable;
children are immutable
D. No difference
Answer: A
Explanation: children
is a special prop used for passing nested elements, while other props are
explicitly passed.
What is the primary
purpose of portals in React?
A. To render components
outside the DOM hierarchy
B. To manage context
C. To bind event
handlers
D. To style nested
components
Answer: A
Explanation: Portals
are used to render children into a different part of the DOM, outside the
parent component's DOM hierarchy.
What does a
"render prop" pattern do?
A. Passes JSX to be
rendered by a child component
B. Provides inline
styling to components
C. Renders static HTML
D. Combines state and
props
Answer: A
Explanation: The render
prop pattern passes a function that returns JSX, enabling component composition
dynamically.
Best Practices
Why should components
be small and focused?
A. To improve code
readability and maintainability
B. To reduce
performance issues
C. To minimize bugs
D. All of the above
Answer: D
Explanation: Small and
focused components enhance readability, debugging, and performance.
Why use defaultProps in
React components?
A. To provide fallback
values for props
B. To improve
performance
C. To enable
memoization
D. To validate data
types
Answer: A
Explanation:
defaultProps defines fallback values for props if none are provided.
How do you ensure a
component renders efficiently?
A. Use React.memo
B. Optimize state
updates
C. Avoid unnecessary
re-renders
D. All of the above
Answer: D
Explanation:
Memoization, efficient state management, and avoiding redundant renders ensure
efficient components.
Real-World Scenarios
How do you design a
button component to handle multiple actions?
A. Use multiple onClick
props
B. Pass a function as a
prop to the button
C. Define the actions
in state
D. Use useEffect
Answer: B
Explanation: Passing a
handler function as a prop enables the button to perform different actions
dynamically.
What is the best
practice for managing form data in a React application?
A. Use controlled
components
B. Use uncontrolled
components
C. Use inline styles
D. Avoid using forms
Answer: A
Explanation: Controlled
components manage form state via React, ensuring better control and validation.
Let me know if you’d
like to extend this further with more specific scenarios!
You said:
yes
ChatGPT said:
ChatGPT
Continuing with MCQs on
real-world scenarios, testing, performance, advanced React concepts, and
anti-patterns:
Real-World Scenarios
Which React hook is
most suitable for fetching data when a component mounts?
A. useState
B. useEffect
C. useContext
D. useReducer
Answer: B
Explanation: useEffect
is commonly used to fetch data or perform side effects when the component
mounts.
How can you implement a
dark mode toggle in React?
A. Use conditional
rendering based on a state variable
B. Use CSS-only
solutions
C. Create separate
components for light and dark modes
D. Both A and B
Answer: D
Explanation: Dark mode
toggling can be implemented via state and conditional rendering or a
combination of CSS variables.
What is the most
efficient way to handle large lists in React?
A. Render all items at
once
B. Use pagination or
infinite scrolling
C. Use a setTimeout to
delay rendering
D. Store the list in
localStorage
Answer: B
Explanation: Pagination
or infinite scrolling optimizes performance by rendering only a subset of items
at a time.
Which React concept can
be used to manage modal dialogs effectively?
A. Context API
B. Portals
C. HOCs
D. State lifting
Answer: B
Explanation: Portals
allow modals to be rendered outside the main DOM hierarchy, making them ideal
for managing modals.
How do you handle
errors gracefully in React?
A. Use try-catch blocks
in every function
B. Use Error Boundaries
C. Avoid state updates
D. Use the useState
hook
Answer: B
Explanation: Error
Boundaries handle rendering errors in React components and display fallback
UIs.
Testing in React
What is the primary
goal of unit testing in React?
A. To check integration
with APIs
B. To validate
individual component functionality
C. To check browser
compatibility
D. To test the entire
application flow
Answer: B
Explanation: Unit
testing focuses on testing individual components to ensure they work as
expected.
Which testing library
is widely used with React?
A. Jest
B. Mocha
C. Jasmine
D. PyTest
Answer: A
Explanation: Jest is a
popular JavaScript testing framework commonly used with React.
What does the render
method of React Testing Library do?
A. Renders a component
to the DOM for testing
B. Initializes the
React app
C. Sets up routing for
the app
D. Handles API mocking
Answer: A
Explanation: The render
method simulates rendering a React component in a test environment.
What is the purpose of
the act function in testing?
A. To simulate user
interactions
B. To wrap updates
ensuring React processes them before assertions
C. To mock API
responses
D. To test component
lifecycle methods
Answer: B
Explanation: act
ensures all updates are processed before assertions in tests.
Which hook is most
useful when testing side effects in a component?
A. useState
B. useEffect
C. useRef
D. useContext
Answer: B
Explanation: useEffect
handles side effects, making it essential in tests that involve them.
Performance
Optimization
What does React.memo
do?
A. Prevents unnecessary
re-renders of a component
B. Stores values
persistently across renders
C. Optimizes large
lists rendering
D. Simplifies state
updates
Answer: A
Explanation: React.memo
wraps components to prevent re-renders when props don't change.
Which of the following
improves performance in React applications?
A. Using dynamic
imports for code splitting
B. Debouncing or
throttling events
C. Avoiding inline
functions and objects in JSX
D. All of the above
Answer: D
Explanation: All these
techniques improve React app performance by reducing unnecessary renders or
delays.
What does lazy loading
in React accomplish?
A. Speeds up the
initial load time
B. Loads all components
at once
C. Prevents the need
for React Router
D. Updates state
asynchronously
Answer: A
Explanation: Lazy
loading defers the loading of components until they are needed, improving
initial load performance.
What does the React
Profiler API measure?
A. Code quality
B. Component rendering
performance
C. API response times
D. Unit test coverage
Answer: B
Explanation: The
Profiler API helps measure rendering performance, identifying bottlenecks in
React components.
Advanced React Concepts
What is the primary use
of Context in React?
A. To replace Redux
B. To manage global
state
C. To style components
D. To optimize
rendering
Answer: B
Explanation: Context
provides a way to pass data through the component tree without props drilling.
What is an HOC
(Higher-Order Component)?
A. A function that
transforms state
B. A component that
returns another component
C. A built-in React
hook
D. A feature of class
components only
Answer: B
Explanation: HOCs are
functions that take a component and return a new component, often used for
cross-cutting concerns.
What is the
significance of keys in React?
A. To optimize
rendering performance in lists
B. To identify
components uniquely in state management
C. To access DOM
elements
D. To style components
Answer: A
Explanation: Keys help
React identify which items have changed, improving performance during
re-renders.
What does Suspense
allow you to do in React?
A. Delay rendering
while waiting for something (e.g., data)
B. Suspend state
updates
C. Optimize API
responses
D. Trigger animations
Answer: A
Explanation: Suspense
is used to show fallback content while waiting for components to load
asynchronously.
Anti-Patterns
Why is it considered an
anti-pattern to directly mutate state?
A. React doesn't detect
changes and won't re-render
B. It leads to
performance degradation
C. It can cause memory
leaks
D. React throws an
error
Answer: A
Explanation: Directly
mutating state bypasses React's tracking, preventing re-renders.
What is an example of
props drilling?
A. Passing props
through multiple layers unnecessarily
B. Using defaultProps
for all components
C. Passing props to
sibling components
D. Using Context API to
manage state
Answer: A
Explanation: Props
drilling occurs when data is passed through components that don't need it,
increasing complexity.
Why should inline
functions in JSX be minimized?
A. They create new
references on every render, causing re-renders
B. They slow down initial
render times
C. They require more
memory
D. They throw warnings
in strict mode
Answer: A
Explanation: Inline
functions create new references each time, leading to potential performance
issues.
Let me know if you’d
like more MCQs on specific subtopics!
You said:
yes
ChatGPT said:
ChatGPT
Here is the
continuation of MCQs focusing on Real-World Scenarios, Testing, Performance
Optimization, Advanced React Concepts, and Anti-Patterns:
Real-World Scenarios
(Continued)
Which of the following
methods is recommended for handling form inputs in React?
A. Directly modifying
the DOM
B. Using useRef to
access input values
C. Using controlled
components
D. Using localStorage
to persist form data
Answer: C
Explanation: Controlled
components ensure React handles form inputs by managing the form state.
What is the advantage
of using React Router in a single-page application (SPA)?
A. Enables client-side
routing without page reloads
B. Prevents the need
for API calls
C. Forces a page
refresh for every route change
D. Automatically
handles server-side rendering
Answer: A
Explanation: React
Router allows navigation between views in an SPA without reloading the page,
offering a seamless user experience.
What strategy can be
employed to improve performance when dealing with large amounts of data in
React?
A. Use pagination
B. Use server-side
rendering
C. Use Web Workers for
data processing
D. All of the above
Answer: D
Explanation: Each of
these strategies improves performance by reducing the load on the browser,
either through pagination, rendering on the server, or delegating processing to
background tasks.
When should you use
React.lazy() for code splitting?
A. When the component
is needed immediately on page load
B. To load critical CSS
only
C. When components
should be loaded only when they are required
D. For better state
management
Answer: C
Explanation:
React.lazy() allows for lazy loading components only when they are needed,
which reduces the initial bundle size and speeds up page load.
How would you improve
performance for a component with frequent state updates that impacts other
components?
A. Use React.memo to
avoid re-renders
B. Use useCallback to
memoize functions
C. Lift the state to
the nearest common ancestor
D. All of the above
Answer: D
Explanation: All of
these methods can optimize rendering performance by minimizing unnecessary
re-renders.
Testing in React
(Continued)
What is the purpose of
mocking API requests in tests?
A. To simulate API
responses during testing
B. To check API server
performance
C. To avoid making real
API calls during tests
D. Both A and C
Answer: D
Explanation: Mocking
API requests simulates responses without hitting actual APIs, ensuring tests
are isolated from external factors.
In React Testing
Library, which query is used to find an element by its text content?
A. getByText
B. getByTestId
C. getByClassName
D. getByLabelText
Answer: A
Explanation: getByText
is used to query elements based on their text content.
What is the cleanup
function in React testing?
A. To clean up mock API
responses
B. To reset state
between tests
C. To unmount
components and clear the DOM after tests
D. To remove event
listeners
Answer: C
Explanation: The
cleanup function is automatically called after each test to ensure the DOM is
cleaned up, avoiding side effects between tests.
Which of the following
is not a recommended testing approach in React?
A. Testing individual
components with isolated mock data
B. Testing components
only in real browser environments
C. Writing tests that
simulate user interaction
D. Testing components
with integration tests
Answer: B
Explanation: While real
browser tests can be useful, it's not recommended to only test components in
real browsers as it can slow down the testing process. Mock environments or
simulated browsers (like Jest with jsdom) are commonly used.
Which testing strategy
helps identify performance bottlenecks in React applications?
A. Integration testing
B. Performance
profiling
C. Snapshot testing
D. Component testing
Answer: B
Explanation:
Performance profiling helps identify rendering bottlenecks by measuring how
long components take to render.
Performance
Optimization (Continued)
What is the benefit of
React.memo?
A. It optimizes
functional component re-renders by comparing props
B. It stores props
persistently across renders
C. It improves API response
times
D. It speeds up data
fetching
Answer: A
Explanation: React.memo
is used to prevent unnecessary re-renders of functional components by shallowly
comparing props.
How does
shouldComponentUpdate help in class components?
A. It improves the
performance of class components by controlling re-renders
B. It sets default
values for state
C. It prevents side
effects
D. It manages component
lifecycle
Answer: A
Explanation:
shouldComponentUpdate allows fine-grained control over when a class component
should re-render based on state or props changes.
Which of the following
will likely improve performance in React?
A. Avoiding inline
functions and objects inside JSX
B. Using useState for
global state management
C. Storing all state in
the Redux store
D. Using the useRef
hook for controlling re-renders
Answer: A
Explanation: Inline
functions and objects inside JSX create new references on every render, which
can trigger unnecessary re-renders.
What does code
splitting in React do?
A. Reduces the size of
the JavaScript bundle loaded at once
B. Divides components
into smaller files for easier testing
C. Generates separate
CSS files for each component
D. Combines multiple
requests into one
Answer: A
Explanation: Code
splitting allows splitting your application’s code into smaller bundles, which
helps to load only the necessary code, improving performance.
What is the role of
React's useDeferredValue hook?
A. Defers expensive
operations until rendering is finished
B. Delays rendering of
components
C. Defers component
mounting
D. Speeds up render
time by delaying updates
Answer: A
Explanation:
useDeferredValue is useful for deferring expensive rendering updates, making it
easier to handle performance-sensitive tasks.
Advanced React Concepts
(Continued)
What is an example of
using useReducer in React?
A. Managing form input
values
B. Managing complex
state logic, such as multiple actions
C. Making HTTP requests
D. Handling animations
Answer: B
Explanation: useReducer
is useful for managing more complex state logic and actions, typically in
scenarios like form management or stateful components with multiple actions.
What feature does React
provide to handle dynamic import and code splitting?
A. React.lazy()
B. React.memo()
C. useContext()
D. Suspense
Answer: A
Explanation:
React.lazy() allows components to be dynamically loaded, reducing the initial
bundle size and enabling code splitting.
What is the purpose of
Suspense in React?
A. It pauses rendering
until a certain condition is met
B. It waits for
asynchronous data or components to load
C. It handles error
boundaries
D. It manages state
changes during asynchronous operations
Answer: B
Explanation: Suspense
provides a way to delay rendering until asynchronous components or data are
ready, displaying a loading state in the meantime.
What is the primary
benefit of using the Context API?
A. It allows props to
be passed through all components in a tree
B. It handles routing
between pages
C. It provides a global
state management solution
D. It optimizes
component rendering
Answer: C
Explanation: The
Context API enables the sharing of state across components without the need for
prop drilling.
Anti-Patterns
(Continued)
Why should you avoid
using a single component for everything in React?
A. It increases
complexity and makes the component hard to maintain
B. It reduces the
flexibility of your app
C. It causes
performance issues by rerendering everything
D. All of the above
Answer: D
Explanation: A single
monolithic component reduces flexibility, complicates maintenance, and causes
performance degradation due to unnecessary re-renders.
Which of the following
is considered an anti-pattern when handling state in React?
A. Keeping all state in
a single component
B. Using context for
every state management task
C. Passing unnecessary
props down the component tree
D. Both A and B
Answer: D
Explanation: Storing
all state in one component or using context for everything can lead to
performance issues and unmanageable code.
What is the problem
with relying on index as a key in React lists?
A. It can lead to
issues with component state when the list changes
B. It increases render
time
C. It prevents
efficient reordering of items
D. It prevents dynamic
content rendering
Answer: A
Explanation: Using
index as a key can cause issues when list items are reordered or removed, as
React may not efficiently track state or props changes.
This section further
expands on concepts related to performance, testing, advanced React features,
and potential pitfalls, helping to refine knowledge and application of React.
You said:
give more 15
ChatGPT said:
ChatGPT
Here are 15 additional
multiple-choice questions (MCQs) based on the advanced React concepts,
real-world scenarios, testing, and performance optimization:
Advanced React Concepts
(Continued)
Which hook should you
use when you need to store a mutable value that does not cause re-renders in React?
A. useState
B. useEffect
C. useReducer
D. useRef
Answer: D
Explanation: useRef
allows you to store mutable values that persist across renders without
triggering a re-render when they are changed.
Which of the following
scenarios would be ideal for using React’s useReducer hook?
A. Handling complex
state updates based on multiple conditions
B. Passing props down
to child components
C. Managing a simple
boolean state
D. Controlling the
visibility of UI elements
Answer: A
Explanation: useReducer
is perfect for managing complex state logic and handling multiple actions,
making it ideal for complex conditions.
What is the role of
useEffect in functional components?
A. It triggers side
effects after a render
B. It triggers an
update of the state
C. It optimizes
component performance
D. It helps to keep the
component's state in sync with props
Answer: A
Explanation: useEffect
runs side effects, such as fetching data or setting up subscriptions, after the
component renders.
When should React.memo
be used for performance optimization?
A. When a component’s
output is based on props and the props rarely change
B. For every component
in the application
C. For components with
no state
D. For components that
always re-render
Answer: A
Explanation: React.memo
is used to prevent re-rendering of a component unless its props change,
improving performance for components with stable props.
What does the
useCallback hook do?
A. It prevents
functions from being recreated on every render
B. It handles side
effects in functional components
C. It returns a
memoized value
D. It forces the
component to re-render
Answer: A
Explanation:
useCallback memoizes functions to prevent them from being recreated on every
render, improving performance.
Performance
Optimization (Continued)
How can you optimize
the performance of React lists with many items?
A. Use the key prop
efficiently
B. Use virtualization
or windowing libraries like react-window
C. Use React.memo to
avoid unnecessary re-renders
D. All of the above
Answer: D
Explanation: All of
these strategies help in improving performance by reducing unnecessary
re-renders and optimizing rendering of large lists.
Which of the following
methods can be used to optimize React component rendering for expensive
calculations?
A. Use useMemo to
memoize the calculated result
B. Use useState instead
of useEffect
C. Use setState in the
render method
D. Use useRef to avoid
re-renders
Answer: A
Explanation: useMemo is
used to memoize expensive calculations and avoid redoing the calculation unless
its dependencies change.
What is the main
purpose of the React.PureComponent class in React?
A. To avoid unnecessary
state changes
B. To prevent
re-renders by performing shallow comparison of props and state
C. To optimize the
virtual DOM
D. To handle lifecycle
methods more efficiently
Answer: B
Explanation:
React.PureComponent automatically handles the shallow comparison of props and
state to prevent unnecessary re-renders.
What does the
useImperativeHandle hook allow you to do?
A. Expose a method or
property to parent components
B. Trigger a re-render
of the component
C. Manipulate component
state directly
D. Manage side effects
within the component
Answer: A
Explanation:
useImperativeHandle allows you to expose specific methods or properties to the
parent component when using forwardRef.
How can you avoid
unnecessary rendering when a child component receives unchanged props?
A. Use React.memo for
the child component
B. Use
shouldComponentUpdate in the parent component
C. Use the key prop to
force re-renders
D. Use useEffect to
skip unnecessary updates
Answer: A
Explanation: React.memo
ensures that a child component does not re-render unless its props change, improving
performance.
Testing in React
(Continued)
Which of the following
methods is used to simulate a user click in React Testing Library?
A. fireEvent.click()
B. simulateClick()
C. triggerEvent()
D. simulateUserAction()
Answer: A
Explanation: fireEvent.click()
is used to simulate a user click event in React Testing Library.
What is the purpose of
snapshot testing in React?
A. To check if the
component renders the same output on each test run
B. To test the
performance of a component
C. To validate component
props
D. To check API
responses
Answer: A
Explanation: Snapshot
testing ensures that a component’s output remains consistent across test runs.
Which of the following
methods is used to test if an element is present in the DOM with React Testing
Library?
A.
expect(element).toBeInTheDocument()
B.
expect(element).toBeVisible()
C.
expect(element).toHaveTextContent()
D.
expect(element).toBeEmpty()
Answer: A
Explanation:
toBeInTheDocument() is used to check if an element is present in the DOM in
React Testing Library.
In unit testing, which
of the following is a good practice for handling async operations in React
components?
A. Using setTimeout to
simulate delays
B. Mocking the API call
with a promise
C. Avoiding the use of
promises in components
D. Using useEffect to
trigger tests
Answer: B
Explanation: Mocking
API calls with promises allows you to control the behavior of async operations
in unit tests.
Which testing strategy
is best for testing components in isolation?
A. Integration testing
B. Unit testing
C. End-to-end testing
D. Load testing
Answer: B
Explanation: Unit
testing is best for testing components in isolation, focusing on individual units
of code and their expected behavior.
