0% found this document useful (0 votes)
1 views54 pages

Module 4 Answers

The document explains the concepts of state and props in React, highlighting their roles in managing and transferring data between components. It covers the use of props for passing data from parent to child components and the use of state for storing dynamic data within components. Additionally, it discusses lifting state up for shared data access among components, event handling, and the differences between stateless and stateful components.
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)
1 views54 pages

Module 4 Answers

The document explains the concepts of state and props in React, highlighting their roles in managing and transferring data between components. It covers the use of props for passing data from parent to child components and the use of state for storing dynamic data within components. Additionally, it discusses lifting state up for shared data access among components, event handling, and the differences between stateless and stateful components.
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

Module 4

State and Props in React

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.

• State is used to store and manage data within a 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.

Props are similar to function arguments in JavaScript.

Example of Props

import React from "react";

function Student(props) {

return (

<div>

<h2>Name: {[Link]}</h2>

</div>

);
}

function App() {

return (

<Student name="Shreya" />


);
}

export default App;

Output

Name: Shreya

Explanation of Props

Part Explanation

name="Shreya" Parent component passes data as props.

[Link] Child component receives and displays the data.

Read-Only Child component cannot modify props directly.

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

import React, { useState } from "react";

function Counter() {

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

return (

<div>

<h2>Count: {count}</h2>

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

Increase

</button>
</div>

);
}

export default Counter;

Output

Count: 0

After button click:


Count: 1

Lifting State Up in React

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.

Why Lifting State Up is Needed

Lifting state up is needed when:

• Multiple components need the same data

• Child components need to communicate with each other

• Data should remain synchronized between components

• State management needs to be centralized

It helps maintain a single source of truth in React applications.

Example Scenario

Suppose there are two child components:

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.

Program Demonstrating Lifting State Up

Child Component 1 – [Link]

import React from "react";

function InputBox(props) {

return (

<div>

<input
type="text"
placeholder="Enter Name"
value={[Link]}
onChange={(e) =>
[Link]([Link])
}
/>

</div>

);
}

export default InputBox;

Child Component 2 – [Link]

import React from "react";

function Display(props) {

return (

<div>

<h2>Entered Name:</h2>

<p>{[Link]}</p>

</div>

);
}

export default Display;

Parent Component – [Link]

import React, { useState } from "react";

import InputBox from "./InputBox";


import Display from "./Display";

function App() {

// State stored in parent component


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

return (

<div>

<h1>Lifting State Up Example</h1>

<InputBox
name={name}
setName={setName}
/>

<Display
name={name}
/>

</div>

);
}

export default App;

Output

Lifting State Up Example

Enter Name: Shreya

Entered Name:
Shreya
Explanation of the Program

Component Explanation

App Component Parent component storing shared state.

useState() Creates the name state variable.

setName() Updates the state dynamically.

InputBox Component Receives state and setter function using props.

Display Component Receives and displays shared state using props.

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:

• CamelCase event names

• JSX syntax

• Functions as event handlers

Examples of React events:

• onClick

• onChange

• onSubmit

• onMouseOver

• onKeyDown

How Events are Handled in React

1. Create an event handling function.

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.

Syntax of Event Handling

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

Here:

• onClick is the event listener

• handleClick is the event handler function

Simple Form Handling Example Using Event Listeners

Program

import React, { useState } from 'react';

import './[Link]';

function App() {

const [text, setText] = useState('');

const handleChange = (event) => {

setText([Link]);

};

return (

<div className="App">

<h1>Dynamic Text Display</h1>

<input

type="text"

value={text}

onChange={handleChange}

placeholder="Type something..."

/>

<p>You typed: {text}</p>


</div>

);

export default App;

Output

React Form Handling

Enter your name: Shreya

You Entered: Shreya

Explanation of the Program

Part Explanation

useState() Creates state variable name for storing input data.

handleChange() Executes whenever the user types in the input field.

[Link] Retrieves the current input value.

setName() Updates the state dynamically.

onChange Event listener for handling input changes.

handleSubmit() Executes when the form is submitted.

[Link]() Prevents page refresh during form submission.

onSubmit Event listener attached to the form.

{name} Displays entered text dynamically.

Common React Events

Event Purpose

onClick Triggered when an element is clicked

onChange Triggered when input value changes


Event Purpose

onSubmit Triggered when a form is submitted

onMouseOver Triggered when mouse moves over element

onKeyDown Triggered when keyboard key is pressed

Features of React Event Handling

Feature Explanation

Dynamic Interaction Responds to user actions instantly.

Controlled Components Form inputs can be managed using state.

Automatic UI Updates React re-renders UI when state changes.

Synthetic Events React uses synthetic events for better browser compatibility.

Stateless Components in React

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.

In modern React, stateless components are usually written as functional components.

Example of Stateless Component

import React from "react";

function Welcome(props) {

return (

<h1>Welcome {[Link]}</h1>

);
}

export default Welcome;

Output
Welcome Shreya

Explanation

Part Explanation

Functional Component Created using a simple JavaScript function.

[Link] Receives data from parent component.

No State Component does not use useState() or [Link].

UI Rendering Only displays data passed through props.

Features of Stateless Components

Feature Explanation

No State Management Does not store or modify state data.

Simple Components Easier to write and understand.

Uses Props Receives data from parent components.

Faster Rendering Lightweight and efficient.

Reusable Can display different data using props.

Stateful Components in React

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.

Stateful components are mainly used when:

• User input changes

• Data updates dynamically

• UI interactions occur

• Form handling is required

Stateful components can be created using:

• Class components with [Link]

• Functional components using useState() Hook

Example of Stateful Component


import React, { useState } from "react";

function Counter() {

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

return (

<div>

<h2>Count: {count}</h2>

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

Increase

</button>

</div>

);
}

export default Counter;

Output

Count: 0

After button click:


Count: 1

Explanation

Part Explanation

useState() Creates state variable count.

setCount() Updates state dynamically.

State Management Component stores and updates its own data.

Dynamic Rendering UI updates automatically when state changes.


Stateless Components Stateful Components

Stateless components do not manage or Stateful components manage and store their own
store state data. state data.

They mainly display UI using props received


They handle dynamic data and user interactions.
from parent components.

Stateless components are simpler and easier Stateful components are more complex because they
to maintain. handle state logic.

They use useState() or [Link] for state


They do not use useState() or [Link].
management.

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.

They can manage their own internal data


They depend on parent components for data.
independently.

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.

They can update data using setter functions like


They do not modify data internally.
setState() or setCount().

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.

Stateful components are comparatively harder


They are easier for beginners to understand.
because of state and lifecycle handling.

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

They are ideal for handling forms, APIs, and user


They are ideal for UI display components.
actions.

Stateless components are often called Stateful components are often called container
presentational components. components.

They focus on logic, data handling, and application


They focus mainly on appearance and layout.
behavior.

Stateless components produce the same Stateful components may produce different outputs
output for the same props. as state changes.

Frequent state updates may affect performance if not


They are easier to optimize for performance.
optimized properly.

Stateless components cannot directly trigger Stateful components trigger UI updates whenever
UI updates on their own. state changes.

They often contain more business and application


They contain minimal business logic.
logic.

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.

State updates are performed using:

• setState() in class components

• useState() Hook in functional components

React compares the updated Virtual DOM with the previous Virtual DOM and updates only the
necessary parts of the real DOM, improving performance.

Steps in React State Update Process


Step Explanation

State Change State is updated using setState() or setter functions like setCount().

Virtual DOM Update React creates a new Virtual DOM representation.

Comparison Process React compares old and new Virtual DOM using a diffing algorithm.

Efficient Rendering Only changed elements are updated in the real DOM.

UI Re-rendering Updated UI is displayed automatically to the user.

Example Using Functional Component

import React, { useState } from "react";

function Counter() {

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

const increaseCount = () => {

setCount(count + 1);

};

return (

<div>

<h2>Count: {count}</h2>

<button onClick={increaseCount}>

Increase

</button>

</div>

);
}

export default Counter;

Output
Initially:
Count: 0

After Button Click:


Count: 1

Explanation of the Program

Part Explanation

useState(0) Creates state variable count with initial value 0.

setCount() Updates the state value.

increaseCount() Event handler function for button click.

Re-rendering React automatically updates UI after state change.

State Updates in Class Components

In class components, state is updated using setState().

Example

import React, { Component } from "react";

class Counter extends Component {

constructor() {

super();

[Link] = {

count: 0

};
}

increaseCount = () => {

[Link]({

count: [Link] + 1

});

};
render() {

return (

<div>

<h2>Count: {[Link]}</h2>

<button onClick={[Link]}>

Increase

</button>

</div>

);
}
}

export default Counter;

Asynchronous Behavior of setState()

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.

Because of this behavior:

• The updated state value may not be available immediately after setState()

• Multiple state updates may be combined together for performance optimization

Example Demonstrating Asynchronous Behavior

import React, { Component } from "react";

class Example extends Component {

constructor() {

super();

[Link] = {

count: 0
};
}

updateCount = () => {

[Link]({

count: [Link] + 1

});

[Link]([Link]);

};

render() {

return (

<div>

<h2>{[Link]}</h2>

<button onClick={[Link]}>

Update

</button>

</div>

);
}
}

export default Example;

Explanation

When the button is clicked:

Displayed UI:
1

Console Output:
0
The console prints the old value because setState() updates the state asynchronously.

Correct Way Using Callback

[Link](

{
count: [Link] + 1
},

() => {

[Link]([Link]);

);

The callback executes after the state update is completed.

Functional Update Method

React also provides a safer method for updating state based on previous state.

[Link]((prevState) => ({

count: [Link] + 1

}));

This avoids problems caused by asynchronous updates.

Why React Uses Asynchronous State Updates

Reason Explanation

Better Performance React batches multiple updates together.

Efficient Rendering Prevents unnecessary DOM updates.

Faster UI Updates Improves application responsiveness.

Optimized Rendering Updates only required UI elements.

Features of React State Updates


Feature Explanation

Automatic Re-rendering UI updates automatically when state changes.

Virtual DOM Optimization React updates only changed elements.

Asynchronous Updates Improves performance using batching.

Dynamic UI Handling Enables interactive applications.

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.

Basic Structure of REST API

Client Request

Express Route

Request Handling

JSON Response

Steps to Create REST API Using Express


Step Explanation

Install Express Install Express package using npm

Create Server Initialize Express application

Define Routes Create GET and POST endpoints

Handle Requests Process incoming client requests

Send Responses Return JSON data to client

Start Server Run server on a specific port

const express = require("express");

const app = express();

// Middleware for JSON data

[Link]([Link]());

// GET Route

[Link]("/users", (req, res) => {

[Link]({

message: "GET Request Successful",

users: ["Shreya", "Rahul", "Anu"]

});

});

// POST Route

[Link]("/users", (req, res) => {


const user = [Link];

[Link]({

message: "POST Request Successful",

user: user

});

});

// Starting Server

[Link](5000, () => {

[Link]("Server running on port 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.

GraphQL mainly uses:

• Queries → To fetch data

• Mutations → To modify data

• Subscriptions → For real-time updates


Unlike REST APIs, GraphQL usually works with a single endpoint.

Example of GraphQL Query

{
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

In REST APIs, different endpoints are created for different resources.

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.

Clients can request specific fields and avoid


REST APIs may return extra or insufficient data.
unnecessary data.

GraphQL reduces over-fetching and under- REST APIs commonly face over-fetching and under-
fetching problems. fetching issues.

Data fetching is less flexible because responses are


Data fetching is more flexible and efficient.
predefined.

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 simplifies API versioning because


REST APIs often create multiple API versions like
fields can be added without changing
/v1, /v2.
endpoints.

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.

A GraphQL schema mainly contains:

• Types

• Fields

• Queries

• Mutations

• Relationships between objects


Example of GraphQL Schema

type Student {

id: ID
name: String
course: String
semester: Int

type Query {

student: Student

Explanation of Schema

Part Explanation

type Student Defines a custom object type called Student.

id: ID Field named id with data type ID.

name: String Field storing text data.

semester: Int Field storing integer value.

type Query Defines available query operations.

student: Student Returns a Student object.

Field Specification in GraphQL

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.

Example of Field Specification

type Book {
title: String
author: String
price: Float

Explanation

Field Type Purpose

title String Stores book title

author String Stores author name

price Float Stores book price

Each field has a specific type that ensures data consistency and validation.

Field Arguments Example

GraphQL fields can also accept arguments.

type Query {

student(id: ID): Student

Here:

• student is a query field

• id is an argument

• Student is the return type

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.

Example of Introspection Query

{
__schema {
types {
name
}
}
}

Output

{
"data": {
"__schema": {
"types": [
{
"name": "Student"
},
{
"name": "Query"
}
]
}
}
}

Uses of Introspection

Use Explanation

API Documentation Automatically generates API documentation

Schema Exploration Helps developers understand API structure

Tool Integration Used in GraphQL IDEs like GraphiQL and Apollo

Query Validation Ensures valid query creation

GraphQL Type System

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

Scalar types represent single values.

Scalar Type Description

String Text data

Int Integer numbers

Float Decimal numbers

Boolean True or False values

ID Unique identifier

Example

type Student {

id: ID
name: String
age: Int
cgpa: Float
active: Boolean

Object Types

Object types combine multiple fields together.

type Student {

name: String
course: String

}
List Types

List types store multiple values.

type Student {

subjects: [String]

Here:

• [String] represents a list of strings.

Non-Null Types

Non-null types ensure values cannot be null.

type Student {

name: String!

The ! symbol means the field is mandatory.

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.

List API in GraphQL

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"
}
]
}
}

This query fetches a list of students from the GraphQL server.

Program

import React, { useState } from "react";

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("");

const [course, setCourse] = useState("");

// useMutation Hook
const [addStudent] =
useMutation(ADD_STUDENT);

// Form Submit Function


const handleSubmit = (event) => {

[Link]();

addStudent({

variables: {

name: name,
course: course

});

alert("Student Added Successfully");


};

return (

<div>

<h1>Create API Using GraphQL</h1>

<form onSubmit={handleSubmit}>

<input
type="text"
placeholder="Enter Name"
value={name}
onChange={(e) =>
setName([Link])
}
/>

<br /><br />

<input
type="text"
placeholder="Enter Course"
value={course}
onChange={(e) =>
setCourse([Link])
}
/>

<br /><br />

<button type="submit">

Add Student

</button>

</form>

</div>

);
}

export default App;


Explanation of the Program

Part Explanation

useState() Stores form input values dynamically.

gql Used to write GraphQL mutation query.

ADD_STUDENT Mutation for creating a new student record.

useMutation() Apollo Hook used to execute GraphQL mutations.

variables Sends dynamic data to the GraphQL server.

handleSubmit() Handles form submission event.

[Link]() Prevents page refresh after form submission.

setName() and setCourse() Updates input field values dynamically.

Working of the Program

1. The user enters student name and course in the form.

2. React stores the values using useState().

3. When the form is submitted, handleSubmit() executes.

4. useMutation() sends the GraphQL mutation request to the server.

5. The server creates a new student record.

6. A success message is displayed after insertion.

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.

GraphQL Query Variables


Query variables are dynamic values passed separately from the query. Instead of hardcoding values
directly inside queries, variables make queries reusable and more secure.

GraphQL variables are commonly used for:

• Dynamic user input

• Search operations

• Filtering data

• Mutations (Create, Update, Delete)

Syntax of Query Variables

query GetStudent($id: ID!) {

student(id: $id) {

name
course

Variable Values

{
"id": "1"
}

Explanation

Part Explanation

$id Variable name

ID! Variable type (! means required)

student(id: $id) Passes variable value dynamically

Separate JSON Object Variable values are sent separately from query

Example Response

{
"data": {
"student": {
"name": "Shreya",
"course": "BE"
}
}
}

Advantages of Query Variables

Advantage Explanation

Reusable Queries Same query can be used with different values

Better Security Prevents query injection problems

Cleaner Queries Separates query logic from input data

Dynamic Data Fetching Allows flexible API requests

Custom Scalar Types in GraphQL

GraphQL provides built-in scalar types such as:

• String

• Int

• Float

• Boolean

• ID

However, sometimes applications require special data formats like:

• Date

• Time

• Email

• URL

In such cases, GraphQL allows developers to create Custom Scalar Types.

Custom scalar types define how specific values are validated, stored, and returned.

Example of Custom Scalar Type

scalar Date

Here, Date is a custom scalar type.


Example Schema Using Custom Scalar

scalar Date

type Student {

id: ID
name: String
joinedDate: Date

Explanation

Field Type Purpose

id ID Unique identifier

name String Student name

joinedDate Date Custom date field

Custom Scalar Resolver Example

const { GraphQLScalarType } = require("graphql");

const DateScalar = new GraphQLScalarType({

name: "Date",

serialize(value) {

return [Link]();

});

Explanation of Resolver

Part Explanation

GraphQLScalarType Creates custom scalar type

name: "Date" Defines scalar type name


Part Explanation

serialize() Converts value before sending response

Difference Between Built-in and Custom Scalars

Built-in Scalars Custom Scalars

Predefined by GraphQL Created by developers

Limited standard data types Supports specialized data formats

Examples: String, Int Examples: Date, Email, URL

No custom validation logic Supports custom validation and formatting

State Initialization and Updating in a React Class Component

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.

State in a class component is:

• Initialized inside the constructor

• Stored using [Link]

• Updated using the setState() method

React automatically re-renders the component whenever the state is updated.

In an Issue Tracker application, state can be used to store:

• List of issues

• Issue status

• Issue count

• Dynamic user input

State Initialization in React Class Component

State is initialized inside the constructor method.

Syntax
constructor() {

super();

[Link] = {

data: value

};

import React from 'react';

import './[Link]';

const issues = [

id: 1,

title: "Bug in login page",

description: "The login page throws an error when submitting invalid credentials.",

status: "Open",

},

id: 2,

title: "UI glitch on homepage",

description: "There is a UI misalignment issue on the homepage for smaller screens.",

status: "Closed",

},

id: 3,

title: "Missing translation for settings page",

description: "The settings page is missing translations for the Spanish language.",

status: "Open",

},

{
id: 4,

title: "Database connection error",

description: "Intermittent database connection issue during peak hours.",

status: "Open",

},

];

const Issue = ({ title, description, status }) => {

return (

<div className="issue">

<h3>{title}</h3>

<p>{description}</p>

<span className={`status ${[Link]()}`}>{status}</span>

</div>

);

};

const App = () => {

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>

);

};

export default App;

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.

Common React events include:

• onClick

• onChange

• onSubmit

• onMouseOver

• onKeyDown

Implementation of Event Handling in React

In React, events are handled by:

1. Creating an event handler function

2. Attaching the function to a JSX element using an event listener

Event names in React use camelCase syntax.

Example:

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

Here:

• onClick is the event listener

• handleClick is the event handler function


Example Program for Event Handling in React

import React, { useState } from "react";

function App() {

const [message, setMessage] =


useState("");

// Event Handler Function


const handleClick = () => {

setMessage("Button Clicked!");

};

return (

<div>

<h1>React Event Handling</h1>

<button onClick={handleClick}>

Click Me

</button>

<h2>{message}</h2>

</div>

);
}

export default App;

Output

React Event Handling

[Click Me]

After clicking button:


Button Clicked!
Explanation of the Program

Part Explanation

useState() Creates state variable for dynamic data

handleClick() Event handler function

onClick React event listener

setMessage() Updates state when button is clicked

Re-rendering React updates UI automatically

Features of React Event Handling

Feature Explanation

Synthetic Events React uses browser-independent event system

CamelCase Syntax Event names use camelCase like onClick

Function-Based Handling Events are handled using JavaScript functions

Automatic UI Updates State changes automatically update UI

Better Performance React optimizes event handling internally

Difference Between React Event Handling and Traditional DOM Event Handling

React Event Handling Traditional DOM Event Handling

React uses Synthetic Events for cross-


Vanilla JavaScript uses native browser DOM events directly.
browser compatibility.

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 automatically binds UI updates


Vanilla JavaScript requires manual DOM manipulation.
with state changes.

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.

Example of Traditional DOM Event Handling

<!DOCTYPE html>
<html>
<body>

<button id="btn">
Click Me
</button>

<script>

[Link]("btn")
.addEventListener("click", function() {

alert("Button Clicked");

});

</script>

</body>
</html>

import React, { Component } from 'react';

class Counter extends Component {

state = { count: 0 };
update = value => {

[Link]({ count: value([Link]) });

};

render() {

return (

<div>

<h1>Count: {[Link]}</h1>

<button onClick={() => [Link](c => c + 1)}>+</button>

<button onClick={() => [Link](c => c - 1)}>-</button>

<button onClick={() => [Link](c => c * 2)}>x2</button>

<button onClick={() => [Link]({ count: 0 })}>Reset</button>

</div>

);

export default Counter;

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() {

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

return ( return (

<div> <div>

<Student name="Shreya" /> <h1>Count: {count}</h1>

</div> <button
onClick={() =>
); setCount(count + 1)
} }>
export default App; Increase

Child Component </button>


import React from "react";
</div>
function Student(props) {
);
return ( }

<h1> export default Counter;

Student Name: {[Link]} Output


Initially:
</h1> Count: 0

); After Button Click:


} Count: 1

export default Student; Explanation of State Program


Part Explanation
Output Creates state variable with initial
Student Name: Shreya useState(0)
value 0
Explanation of Props Program count Stores current counter value
Part Explanation setCount() Updates state dynamically
Parent component passes data Re-
name="Shreya" React updates UI automatically
as props rendering
Child component receives the
[Link]
prop
Child component cannot
Read-Only
modify props

[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:

• GET request is used to fetch product data

• POST request is used to create new product data

The API stores product information in an array and sends responses in JSON format.

Program
const express = require("express");

const app = express();

// Middleware for JSON data


[Link]([Link]());

// Product Data
let products = [

{
id: 1,
name: "Laptop",
price: 50000
},

{
id: 2,
name: "Mobile",
price: 20000
}

];

// GET API to fetch products


[Link]("/products", (req, res) => {

[Link](products);

});

// POST API to create product


[Link]("/products", (req, res) => {

const newProduct = [Link];

[Link](newProduct);

[Link]({

message: "Product Added Successfully",

product: newProduct

});

});
// Server Connection
[Link](5000, () => {

[Link]("Server running on port 5000");

});

Explanation of the Program

Part Explanation

require("express") Imports [Link] framework

express() Creates Express application

[Link]() Middleware used to handle JSON data

products Array storing product information

[Link]() Creates GET API for fetching products

[Link](products) Sends product data as JSON response

[Link]() Creates POST API for adding products

[Link] Receives product data from client

[Link]() Adds new product to array

[Link]() Starts the server on port 5000

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:

• The API validates product name and price

• Returns error messages for invalid input

• Handles successful requests properly

Program

const express = require("express");

const app = express();

// Middleware for JSON data


[Link]([Link]());

// Product Array
let products = [];

// POST API with Validation


[Link]("/products", (req, res) => {

const { name, price } = [Link];

// Validation
if (!name || !price) {

return [Link](400).json({

error: "Product name and price are required"

});

// Price Validation
if (price <= 0) {

return [Link](400).json({

error: "Price must be greater than zero"

});

// Creating Product
const newProduct = {

id: [Link] + 1,
name,
price

};

[Link](newProduct);

// Success Response
[Link](201).json({

message: "Product Added Successfully",

product: newProduct

});

});

// GET API
[Link]("/products", (req, res) => {

[Link](products);

});

// Error Handling for Invalid Routes


[Link]((req, res) => {

[Link](404).json({

error: "Route Not Found"

});

});

// Server Connection
[Link](5000, () => {

[Link]("Server running on port 5000");

});

Explanation of the Program


Part Explanation

[Link]() Middleware used to handle JSON request data

[Link] Receives data sent by the client

`if (!name

[Link](400) Sends Bad Request status code

price <= 0 Validates product price

[Link]() Adds valid product data to array

[Link](201) Sends Created status code for successful insertion

[Link]() Fetches all product data

[Link]() Handles invalid routes and errors

[Link]() Starts the Express server

Example Valid POST Request

{
"name": "Laptop",
"price": 50000
}

Success Response

{
"message": "Product Added Successfully",
"product": {
"id": 1,
"name": "Laptop",
"price": 50000
}
}

Example Invalid Request

{
"name": "",
"price": -100
}
Error Response

{
"error": "Price must be greater than zero"
}

You might also like