Module 4 Answers
Module 4 Answers
In React, state and props are two important concepts used to manage and transfer data between
components. They help create dynamic and interactive user interfaces.
• Props are used to pass data from a parent component to a child component.
Both state and props help React update the UI dynamically whenever data changes.
Props in React
Props (Properties) are read-only values passed from a parent component to a child component.
Props help make components reusable because different values can be passed to the same
component.
Example of Props
function Student(props) {
return (
<div>
<h2>Name: {[Link]}</h2>
</div>
);
}
function App() {
return (
Output
Name: Shreya
Explanation of Props
Part Explanation
State in React
State is a built-in object used to store dynamic data inside a component. State can change over time,
and whenever the state changes, React automatically re-renders the UI.
Functional components mainly use the useState() Hook for state management.
Example of State
function Counter() {
return (
<div>
<h2>Count: {count}</h2>
<button
onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
Output
Count: 0
Lifting state up in React is the process of moving the state from a child component to its parent
component so that multiple child components can share and use the same data.
In React, data flows from parent to child using props. When two or more child components need
access to the same state or need to communicate with each other, the common state is moved to
the nearest common parent component. This process is called lifting state up.
Example Scenario
1. Input Component
2. Display Component
When the user types text in the input component, the display component should show the same text
dynamically.
Since both child components need the same data, the state is moved to the parent component.
function InputBox(props) {
return (
<div>
<input
type="text"
placeholder="Enter Name"
value={[Link]}
onChange={(e) =>
[Link]([Link])
}
/>
</div>
);
}
function Display(props) {
return (
<div>
<h2>Entered Name:</h2>
<p>{[Link]}</p>
</div>
);
}
function App() {
return (
<div>
<InputBox
name={name}
setName={setName}
/>
<Display
name={name}
/>
</div>
);
}
Output
Entered Name:
Shreya
Explanation of the Program
Component Explanation
Shared State Both child components use the same parent state.
Events in React are actions triggered by user interactions such as clicking buttons, typing in input
fields, submitting forms, moving the mouse, or pressing keyboard keys. React handles events using
event handlers, which are functions executed when an event occurs.
React event handling is similar to JavaScript DOM events, but React uses:
• JSX syntax
• onClick
• onChange
• onSubmit
• onMouseOver
• onKeyDown
2. Attach the function to a JSX element using an event listener such as onClick or onChange.
3. When the event occurs, React executes the function automatically.
<button onClick={handleClick}>
Click Me
</button>
Here:
Program
import './[Link]';
function App() {
setText([Link]);
};
return (
<div className="App">
<input
type="text"
value={text}
onChange={handleChange}
placeholder="Type something..."
/>
);
Output
Part Explanation
Event Purpose
Feature Explanation
Synthetic Events React uses synthetic events for better browser compatibility.
Stateless components are React components that do not manage or store their own state. They
simply receive data through props and display the UI based on that data. Stateless components are
also called presentational components because they are mainly responsible for displaying
information.
function Welcome(props) {
return (
<h1>Welcome {[Link]}</h1>
);
}
Output
Welcome Shreya
Explanation
Part Explanation
Feature Explanation
Stateful components are components that manage and store their own state. These components can
update data dynamically and re-render the UI whenever the state changes.
• UI interactions occur
function Counter() {
return (
<div>
<h2>Count: {count}</h2>
<button
onClick={() =>
setCount(count + 1)
}>
Increase
</button>
</div>
);
}
Output
Count: 0
Explanation
Part Explanation
Stateless components do not manage or Stateful components manage and store their own
store state data. state data.
Stateless components are simpler and easier Stateful components are more complex because they
to maintain. handle state logic.
Stateless components are mainly used for Stateful components are used for dynamic behavior
presentation purposes. and interactivity.
They generally render static content. They render dynamic content that changes over time.
Stateless components are lightweight and Stateful components require more processing
faster. because state updates trigger re-rendering.
Easier to test and debug due to simpler logic. Slightly harder to debug because of state handling.
Example: Header, Footer, Welcome message. Example: Counter, Login form, Todo application.
Stateless components are usually written as Stateful components can be written using class
simple functional components. components or functional components with Hooks.
Stateless components are more reusable Stateful components are less reusable if tightly
because they only display data. coupled with specific state logic.
They receive data from outside through They can both receive props and maintain their own
props only. state.
Stateless components have less memory Stateful components use more memory because they
usage. maintain state information.
Stateless components do not contain lifecycle Stateful components commonly use lifecycle methods
methods in traditional class-based React. or Hooks like useEffect().
Stateless Components Stateful Components
Stateless components are often called Stateful components are often called container
presentational components. components.
Stateless components produce the same Stateful components may produce different outputs
output for the same props. as state changes.
Stateless components cannot directly trigger Stateful components trigger UI updates whenever
UI updates on their own. state changes.
Stateless components are commonly used Stateful components are commonly used with
with reusable UI elements like cards and dashboards, authentication systems, and interactive
buttons. applications.
In React, state is used to store dynamic data inside a component. When the state changes, React
automatically updates and re-renders the user interface to reflect the new data. React handles state
updates efficiently using its Virtual DOM mechanism.
React compares the updated Virtual DOM with the previous Virtual DOM and updates only the
necessary parts of the real DOM, improving performance.
State Change State is updated using setState() or setter functions like setCount().
Comparison Process React compares old and new Virtual DOM using a diffing algorithm.
Efficient Rendering Only changed elements are updated in the real DOM.
function Counter() {
setCount(count + 1);
};
return (
<div>
<h2>Count: {count}</h2>
<button onClick={increaseCount}>
Increase
</button>
</div>
);
}
Output
Initially:
Count: 0
Part Explanation
Example
constructor() {
super();
[Link] = {
count: 0
};
}
increaseCount = () => {
[Link]({
count: [Link] + 1
});
};
render() {
return (
<div>
<h2>Count: {[Link]}</h2>
<button onClick={[Link]}>
Increase
</button>
</div>
);
}
}
React state updates using setState() are asynchronous. This means React does not update the state
immediately after calling setState(). Instead, React schedules the update and performs it efficiently in
batches.
• The updated state value may not be available immediately after setState()
constructor() {
super();
[Link] = {
count: 0
};
}
updateCount = () => {
[Link]({
count: [Link] + 1
});
[Link]([Link]);
};
render() {
return (
<div>
<h2>{[Link]}</h2>
<button onClick={[Link]}>
Update
</button>
</div>
);
}
}
Explanation
Displayed UI:
1
Console Output:
0
The console prints the old value because setState() updates the state asynchronously.
[Link](
{
count: [Link] + 1
},
() => {
[Link]([Link]);
);
React also provides a safer method for updating state based on previous state.
[Link]((prevState) => ({
count: [Link] + 1
}));
Reason Explanation
A REST API (Representational State Transfer Application Programming Interface) is a system that
allows communication between the client and server using HTTP requests. In web development,
REST APIs are commonly used to send and receive data between frontend applications and backend
servers. [Link] is a lightweight framework built on [Link] that helps developers create REST APIs
easily and efficiently.
The basic structure of a REST API in Express includes creating an Express server, defining routes,
handling client requests, processing data, and sending responses in JSON format. Express uses
different HTTP methods such as GET, POST, PUT, and DELETE to perform various operations. Among
these, GET is mainly used to retrieve data from the server, while POST is used to send new data from
the client to the server.
In [Link], the server is created using the express() function. Routes are then defined using
methods such as [Link]() and [Link](). Each route contains a callback function that handles the
request and response objects. The request object (req) contains information sent by the client, while
the response object (res) is used to send data back to the client.
REST APIs commonly exchange data in JSON (JavaScript Object Notation) format because it is
lightweight, readable, and easy for JavaScript applications to process. Express provides the [Link]()
method to send JSON responses easily.
Client Request
↓
Express Route
↓
Request Handling
↓
JSON Response
[Link]([Link]());
// GET Route
[Link]({
});
});
// POST Route
[Link]({
user: user
});
});
// Starting Server
[Link](5000, () => {
});
GraphQL
GraphQL is a query language and API technology developed by Facebook for building efficient APIs. It
allows clients to request only the specific data they need from the server instead of receiving fixed
data responses. GraphQL acts as an alternative to REST APIs and provides flexible and optimized data
fetching.
In GraphQL, the client sends a query to the server, and the server returns only the requested data in
a single response. This reduces unnecessary data transfer and improves application performance.
{
student {
name
course
}
}
Example Response
{
"data": {
"student": {
"name": "Shreya",
"course": "BE"
}
}
}
The client receives only the requested fields (name and course) instead of the complete object.
REST API
REST API (Representational State Transfer API) is an architectural style used for communication
between client and server using HTTP methods such as:
• GET
• POST
• PUT
• DELETE
Example:
/users
/products
/orders
REST APIs usually return fixed data structures from the server.
GraphQL REST API
GraphQL is a query language for APIs that REST API is an architectural style where the server
allows clients to request only required data. provides fixed data responses through endpoints.
GraphQL uses a single endpoint for handling all REST APIs use multiple endpoints for different
requests. resources.
GraphQL reduces over-fetching and under- REST APIs commonly face over-fetching and under-
fetching problems. fetching issues.
GraphQL queries are usually sent using POST REST APIs use different HTTP methods like GET,
requests. POST, PUT, and DELETE.
Strongly typed schema defines available data REST APIs usually do not enforce a strict schema
and operations clearly. structure.
GraphQL combines multiple resource requests REST APIs may require multiple requests for related
into a single query. resources.
Better suited for modern frontend applications Suitable for traditional web services and simple
and mobile apps. APIs.
GraphQL provides precise data fetching and REST APIs may transfer unnecessary data,
improved performance. increasing bandwidth usage.
GraphQL gives the client more control over the REST APIs give more control to the server over
response data. returned data.
GraphQL APIs are self-documenting because of REST APIs often require external documentation
their schema system. tools like Swagger.
GraphQL supports real-time updates using REST APIs usually require additional technologies
subscriptions. like WebSockets for real-time communication.
GraphQL allows nested queries for related REST APIs often need separate endpoints for nested
data. resources.
GraphQL is highly efficient for complex REST APIs are simpler and easier for small
applications with interconnected data. applications.
GraphQL minimizes network requests by REST APIs may increase network requests due to
fetching all needed data in one request. multiple endpoints.
GraphQL REST API
GraphQL makes frontend development easier REST APIs may require backend modifications if
because clients can customize responses. frontend data needs change.
GraphQL uses a schema to validate queries REST APIs mainly rely on endpoint logic and
before execution. validation rules.
GraphQL responses always follow a predictable REST API response structures may vary between
structure. endpoints.
GraphQL is commonly used in large-scale REST APIs are widely used in traditional web
applications like Facebook and GitHub. services and public APIs.
GraphQL allows fetching multiple types of REST APIs usually fetch one resource type per
resources in one request. request.
GraphQL queries can become complex if not REST APIs are generally easier to understand and
optimized properly. debug.
GraphQL requires learning schemas, queries, REST APIs are easier for beginners because they use
and resolvers. standard HTTP methods.
GraphQL improves frontend flexibility and REST APIs are more suitable for simple CRUD
scalability. operations.
A GraphQL schema is the core structure of a GraphQL API that defines the types of data, available
fields, relationships between data, and operations that clients can perform. It acts as a contract
between the client and the server, specifying what data can be queried or modified.
The schema is strongly typed, meaning every field and object must have a defined data type.
GraphQL schemas help developers understand the API structure clearly and enable validation of
queries before execution.
• Types
• Fields
• Queries
• Mutations
type Student {
id: ID
name: String
course: String
semester: Int
type Query {
student: Student
Explanation of Schema
Part Explanation
Field specification defines the properties available inside a GraphQL type. Every field has:
1. Field Name
2. Data Type
3. Optional Arguments
Fields determine what data clients can request from the API.
type Book {
title: String
author: String
price: Float
Explanation
Each field has a specific type that ensures data consistency and validation.
type Query {
Here:
• id is an argument
Introspection in GraphQL
Introspection is a special feature in GraphQL that allows clients to inspect and explore the schema
automatically. Using introspection, developers can discover:
• Available types
• Fields
• Queries
• Mutations
• Arguments
• Relationships
GraphQL APIs are self-documenting because of introspection.
{
__schema {
types {
name
}
}
}
Output
{
"data": {
"__schema": {
"types": [
{
"name": "Student"
},
{
"name": "Query"
}
]
}
}
}
Uses of Introspection
Use Explanation
The GraphQL type system defines how data is structured in the API. Every field and operation must
have a specific type.
GraphQL supports:
1. Scalar Types
2. Object Types
3. List Types
4. Non-Null Types
Scalar Types
ID Unique identifier
Example
type Student {
id: ID
name: String
age: Int
cgpa: Float
active: Boolean
Object Types
type Student {
name: String
course: String
}
List Types
type Student {
subjects: [String]
Here:
Non-Null Types
type Student {
name: String!
List API and Create API Integration Using GraphQL with React
In GraphQL, APIs are integrated with React applications to fetch and manipulate data efficiently. A
List API is used to retrieve multiple records from the server, while a Create API is used to add new
data to the server. React applications commonly use GraphQL queries and mutations for performing
these operations.
GraphQL integration with React is usually done using libraries such as:
• Apollo Client
• GraphQL Request
• Relay
Apollo Client is one of the most popular libraries for integrating GraphQL APIs with React
applications.
A List API is used to retrieve multiple records from the server. In GraphQL, this is done using a Query.
Example GraphQL List Query
query {
students {
id
name
course
Example Response
{
"data": {
"students": [
{
"id": "1",
"name": "Shreya",
"course": "BE"
},
{
"id": "2",
"name": "Rahul",
"course": "BCA"
}
]
}
}
Program
import {
gql,
useMutation
} from "@apollo/client";
// GraphQL Mutation
const ADD_STUDENT = gql`
mutation AddStudent(
$name: String!,
$course: String!
){
addStudent(
name: $name,
course: $course
){
id
name
course
`;
function App() {
// State Variables
const [name, setName] = useState("");
// useMutation Hook
const [addStudent] =
useMutation(ADD_STUDENT);
[Link]();
addStudent({
variables: {
name: name,
course: course
});
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Enter Name"
value={name}
onChange={(e) =>
setName([Link])
}
/>
<input
type="text"
placeholder="Enter Course"
value={course}
onChange={(e) =>
setCourse([Link])
}
/>
<button type="submit">
Add Student
</button>
</form>
</div>
);
}
Part Explanation
In GraphQL, query variables and custom scalar types are important features used to make APIs more
flexible, reusable, and strongly typed.
• Query Variables are used to pass dynamic values into GraphQL queries or mutations.
• Custom Scalar Types are user-defined data types used when built-in scalar types are not
sufficient.
These features improve query reusability, validation, and data handling in GraphQL APIs.
• Search operations
• Filtering data
student(id: $id) {
name
course
Variable Values
{
"id": "1"
}
Explanation
Part Explanation
Separate JSON Object Variable values are sent separately from query
Example Response
{
"data": {
"student": {
"name": "Shreya",
"course": "BE"
}
}
}
Advantage Explanation
• String
• Int
• Float
• Boolean
• ID
• Date
• Time
• URL
Custom scalar types define how specific values are validated, stored, and returned.
scalar Date
scalar Date
type Student {
id: ID
name: String
joinedDate: Date
Explanation
id ID Unique identifier
name: "Date",
serialize(value) {
return [Link]();
});
Explanation of Resolver
Part Explanation
In React class components, state is used to store dynamic data that can change during the execution
of the application. State helps React components become interactive by allowing the UI to update
automatically whenever the data changes.
• List of issues
• Issue status
• Issue count
Syntax
constructor() {
super();
[Link] = {
data: value
};
import './[Link]';
const issues = [
id: 1,
description: "The login page throws an error when submitting invalid credentials.",
status: "Open",
},
id: 2,
status: "Closed",
},
id: 3,
description: "The settings page is missing translations for the Spanish language.",
status: "Open",
},
{
id: 4,
status: "Open",
},
];
return (
<div className="issue">
<h3>{title}</h3>
<p>{description}</p>
</div>
);
};
return (
<div className="App">
<h1>Issue Tracker</h1>
<div className="issue-list">
{[Link]((issue) => (
<Issue
key={[Link]}
title={[Link]}
description={[Link]}
status={[Link]}
/>
))}
</div>
</div>
);
};
Event handling in React is the process of responding to user actions such as clicking buttons, typing in
input fields, submitting forms, moving the mouse, or pressing keys. React provides a simple and
efficient way to handle events using event listeners and event handler functions.
React events are similar to JavaScript DOM events, but React uses its own event system called
Synthetic Events. Synthetic events provide consistent behavior across different browsers.
• onClick
• onChange
• onSubmit
• onMouseOver
• onKeyDown
Example:
<button onClick={handleClick}>
Click Me
</button>
Here:
function App() {
setMessage("Button Clicked!");
};
return (
<div>
<button onClick={handleClick}>
Click Me
</button>
<h2>{message}</h2>
</div>
);
}
Output
[Click Me]
Part Explanation
Feature Explanation
Difference Between React Event Handling and Traditional DOM Event Handling
Event names use camelCase syntax such Event names are written in lowercase such as onclick and
as onClick and onChange. onchange.
Event handlers are written inside JSX Event handlers are attached using HTML attributes or
using curly braces. JavaScript methods like addEventListener().
React follows component-based event Traditional DOM handling works directly on HTML
handling. elements.
React improves performance using Vanilla JavaScript updates the real DOM directly, which
Virtual DOM optimization. may be slower.
React Event Handling Traditional DOM Event Handling
React event handling code is more Traditional DOM code can become difficult to manage in
organized and reusable. large applications.
React uses declarative programming Vanilla JavaScript mainly uses imperative programming
style. style.
State updates automatically re-render Developers manually update HTML elements after event
the component UI. execution.
React handles browser compatibility Developers may need additional handling for browser
internally. differences.
<!DOCTYPE html>
<html>
<body>
<button id="btn">
Click Me
</button>
<script>
[Link]("btn")
.addEventListener("click", function() {
alert("Button Clicked");
});
</script>
</body>
</html>
state = { count: 0 };
update = value => {
};
render() {
return (
<div>
<h1>Count: {[Link]}</h1>
</div>
);
This React class component is used to create a simple counter application. The Counter class extends
Component, which allows it to use React features like state and rendering. The state variable count is
initialized to 0 and stores the current counter value. The update() function is created to modify the
count dynamically by using setState(). Different buttons call this function with different operations
such as increment (+1), decrement (-1), and double (*2). The Reset button directly sets the count
back to 0. Inside the render() method, the current count value is displayed using <h1>, and buttons
are provided for user interaction. Whenever a button is clicked, the state updates automatically, and
React re-renders the component to show the updated count value on the screen.
State Props
State is used to store and manage dynamic Props are used to pass data from parent
data within a component. components to child components.
State is mutable, meaning its value can Props are immutable, meaning child
change during execution. components cannot modify them directly.
State is managed inside the component Props are controlled and passed by the
itself. parent component.
State updates can change the UI Props display data received from parent
dynamically. components.
State is local to a particular component. Props can be shared among multiple
components.
State is initialized using useState() or Props are passed as attributes inside
[Link]. component tags.
State is mainly used for user interaction and Props are mainly used for component
dynamic behavior. communication and reusability.
State changes trigger component re- Props changes also cause child components
rendering automatically. to re-render when parent data changes.
State can be updated using setState() or Props cannot be updated directly inside the
setter functions. receiving component.
State stores temporary and changing data. Props store external and read-only data.
State belongs to the component where it is Props belong to the parent component that
created. passes them.
State management increases component Props improve component reusability.
interactivity.
State is commonly used in forms, counters, Props are commonly used for sending titles,
toggles, and dynamic applications. values, functions, and objects.
State can hold and modify application data Props only receive and display passed data.
dynamically.
State is private to the component. Props are public inputs to components.
Stateful components are more interactive Components using only props are generally
and dynamic. simpler and reusable.
State updates happen internally within the Props updates occur externally through
component. parent components.
State is useful for handling events and UI Props are useful for sharing data between
changes. components.
State increases application responsiveness Props maintain unidirectional data flow in
and interactivity. React.
State can exist without props. Props can exist without state.
Example Program for Props Example Program for State
Parent Component import React, { useState } from "react";
import React from "react";
import Student from "./Student"; function Counter() {
return ( return (
<div> <div>
</div> <button
onClick={() =>
); setCount(count + 1)
} }>
export default App; Increase
[Link] is a lightweight [Link] framework used to build REST APIs. A REST API allows
communication between the client and server using HTTP methods such as GET and POST.
In this example:
The API stores product information in an array and sends responses in JSON format.
Program
const express = require("express");
// Product Data
let products = [
{
id: 1,
name: "Laptop",
price: 50000
},
{
id: 2,
name: "Mobile",
price: 20000
}
];
[Link](products);
});
[Link](newProduct);
[Link]({
product: newProduct
});
});
// Server Connection
[Link](5000, () => {
});
Part Explanation
GET Request
GET /products
GET Response
[
{
"id": 1,
"name": "Laptop",
"price": 50000
},
{
"id": 2,
"name": "Mobile",
"price": 20000
}
]
POST Request
{
"id": 3,
"name": "Headphones",
"price": 3000
}
POST Response
{
"message": "Product Added Successfully",
"product": {
"id": 3,
"name": "Headphones",
"price": 3000
}
}
GraphQL REST
GraphQL is a query language and runtime REST is an architectural style used to build
for APIs. web services.
GraphQL uses a single endpoint for all REST uses multiple endpoints for different
requests. resources.
Clients can request only the required fields. Server returns fixed and predefined data
structures.
Reduces over-fetching and under-fetching May return unnecessary or insufficient data.
of data.
Data fetching is flexible and efficient. Data fetching is less flexible because
responses are predefined.
Uses queries, mutations, and subscriptions. Uses HTTP methods such as GET, POST,
PUT, and DELETE.
GraphQL APIs are strongly typed using REST APIs generally do not enforce a strict
schemas. schema.
GraphQL combines multiple resource REST may require multiple requests for
requests into one query. related data.
Better suited for modern frontend and Suitable for simple and traditional web
mobile applications. applications.
Supports real-time updates using Requires additional technologies like
subscriptions. WebSockets for real-time communication.
GraphQL responses contain only requested REST responses may include extra
data. unwanted data.
GraphQL APIs are self-documenting REST APIs usually require external
through introspection. documentation.
API versioning is less required in GraphQL. REST commonly uses API versions like
/v1 and /v2.
GraphQL minimizes network requests and REST may increase bandwidth usage due to
bandwidth usage. multiple endpoints.
Clients have more control over response Server controls the response structure
structure. completely.
GraphQL queries are written by clients REST endpoints are predefined by the
dynamically. server.
GraphQL is ideal for complex and REST is easier to implement for simple
interconnected data. CRUD operations.
GraphQL requires schema definition and REST APIs are simpler and easier for
resolvers. beginners.
GraphQL provides better frontend REST provides simpler backend
flexibility. implementation.
Commonly used in Facebook, GitHub, and Widely used in traditional web services and
modern MERN applications. public APIs.
Example of GraphQL API Example of REST API
Query Request
{ GET /students
student {
name Response
course {
} "id": 1,
} "name": "Shreya",
"course": "BE",
Response "semester": 6,
{ "email": "shreya@[Link]"
"data": { }
"student": { The server returns the complete object even if
"name": "Shreya", only one field is required.
"course": "BE"
}
}
}
Only the requested fields are returned.
Input validation and error handling are important features in REST APIs. Validation ensures that the
client sends correct and complete data, while error handling helps the server respond properly when
invalid data or unexpected problems occur.
In [Link], validation can be performed by checking request data manually or using middleware.
Error handling is implemented using conditional statements and proper HTTP status codes.
In this example:
Program
// Product Array
let products = [];
// Validation
if (!name || !price) {
return [Link](400).json({
});
// Price Validation
if (price <= 0) {
return [Link](400).json({
});
// Creating Product
const newProduct = {
id: [Link] + 1,
name,
price
};
[Link](newProduct);
// Success Response
[Link](201).json({
product: newProduct
});
});
// GET API
[Link]("/products", (req, res) => {
[Link](products);
});
[Link](404).json({
});
});
// Server Connection
[Link](5000, () => {
});
`if (!name
{
"name": "Laptop",
"price": 50000
}
Success Response
{
"message": "Product Added Successfully",
"product": {
"id": 1,
"name": "Laptop",
"price": 50000
}
}
{
"name": "",
"price": -100
}
Error Response
{
"error": "Price must be greater than zero"
}