0% found this document useful (0 votes)
5 views12 pages

FSD 4th

The document provides an overview of key concepts in React, including state management using the useState hook, the useEffect hook for handling side effects, and the distinction between props and state. It also discusses the practice of 'lifting state up' for shared state management among components, and compares GraphQL and REST APIs in terms of structure, strengths, and limitations. Additionally, it includes examples of an Express API for product management, highlighting input validation and error handling.
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)
5 views12 pages

FSD 4th

The document provides an overview of key concepts in React, including state management using the useState hook, the useEffect hook for handling side effects, and the distinction between props and state. It also discusses the practice of 'lifting state up' for shared state management among components, and compares GraphQL and REST APIs in terms of structure, strengths, and limitations. Additionally, it includes examples of an Express API for product management, highlighting input validation and error handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

​1)How does state work in React? Describe how to define and update it.

In React, state is a built-in object used to store dynamic data and control the behavior of a
component. State enables components to respond to user inputs, server responses, or any
other dynamic changes.

1. What is State?
State is mutable, unlike props.
It is local to the component and managed internally.
When the state changes, the component re-renders automatically to reflect the new state in the
UI.

2. Defining State (using useState Hook)


In React functional components, the useState() hook is used to define state variables.

import React, { useState } from 'react';


function Counter() {
const [count, setCount] = useState(0); // count is the state variable
...
}

useState(0) initializes the count with value.


setCount is the function used to update the state.

3. Updating State
State should always be updated using the setter function provided by useState. Direct
modification is not allowed.
<button onClick={() => setCount(count + 1)}>
Increment
</button>
When setCount is called, React updates the state and re-renders the component.

4. Key Point
Each call to useState() returns a stateful value and a function to update it.
Multiple state variables can be declared in one component.
State updates are asynchronous and may be batched for performance.

5. Example Component

import React, { useState } from 'react';


function ToggleButton() {
const [isOn, setIsOn] = useState(true);
return (
<button onClick={() => setIsOn(!isOn)}>
{isOn ? "ON" : "OFF"}
</button>
);
}

6. Conclusion
State is a fundamental concept in React that allows components to be interactive and dynamic.
Understanding how to properly define and update state using useState() is essential for
building effective React applications.

2)Show a React component that uses both useState and useEffect to manage a counter.

React Component Using useState and useEffect to Manage a Counter


React provides hooks like useState and useEffect to manage state and side effects in functional
components.

1. useState Hook
Used to create and manage state variables.
Returns an array with current value and a function to update it.

2. useEffect Hook
Used to perform side effects such as fetching data, setting up timers, or logging.
Executes after every render or when specific dependencies change.

Example: Counter Component with useState and useEffect


import React, { useState, useEffect } from 'react';
function Counter() {
const [count, setCount] = useState(0); // Initializing state

// useEffect to log the count whenever it changes


useEffect(() => {
console.log(`Count updated: ${count}`);
}, [count]); // Dependency array - triggers effect on count change

return (
<div>
<h2>Counter: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}

export default Counter;

Explanation:
useState(0) initializes the count to 0.
setCount(count + 1) increments the counter on button click.
useEffect() logs the value of count each time it changes.
This demonstrates a combination of state management and side effects in a component.

Key Points:
useState is used for local component state.
useEffect is used for handling side effects like logging, API calls, etc.
React automatically re-renders the component when the state changes.

Conclusion:
The Counter component illustrates how useState manages state, and useEffect reacts to
changes in that state, providing a powerful pattern for interactive and reactive user interfaces.

3) Provide an analogy to differentiate between props and state in React.

Analogy to Differentiate Between Props and State in React


In React, both props and state are used to manage data, but they serve different purposes. To
understand their difference clearly, we can use a real-world analogy.

1. Analogy: TV Remote and TV


Imagine a television (TV) component.
The remote control is like props.
The TV’s internal settings (like volume level, input source, etc.) are like state.

Props (Remote Control):


Props are like external inputs to the TV.
The user provides input from the remote (e.g., change channel).
The TV cannot change the remote; it can only react to the input.
Props are read-only and passed from parent to child component.
State (TV's Internal Settings):
State is like the TV's internal configuration.
When you increase volume using the remote, the TV changes its internal state.
Only the TV itself (the component) can manage or change its own state.
State is mutable and controlled within the component.

2. Technical Explanation
Feature Props State
Definition External data passed to a component Internal data managed by the component
Mutability Immutable Mutable
Ownership Controlled by parent component Controlled by the component itself
Use case Configuration Interactive behavior

3. Example in Code
function Greeting(props) {
const [name, setName] = useState(props.initialName);

return (
<div>
<h1>Hello, {name}!</h1>
<button onClick={() => setName("VTU Student")}>Change Name</button>
</div>
);
}

props.initialName is passed externally.

name is internal state, which can be changed with the button.

4. Conclusion
Just like a remote controls a TV, props control the component from outside, while state
represents the component's own internal behavior. Understanding the distinction is key to
building reusable and interactive React components.

4)What does "lifting state up" mean in React? When and why is it done?

1. Introduction
In React, “lifting state up” refers to the practice of moving shared state to the nearest common
ancestor of two or more components that need access to it. This allows multiple components to
synchronize and work with the same state.

2. Why Is It Needed?
When two or more child components need to share or update the same data.
Keeping state in a single, central component avoids inconsistencies.
It promotes data flow from top to bottom, maintaining React’s unidirectional data flow
principle.

3. When Is It Done?
Lifting state is done in the following scenarios:
Two components need to communicate or coordinate.
A child component needs to modify the state, and the sibling needs to reflect that change.
When building controlled components, such as forms with shared validation.

4. Example: Temperature Converter


function Parent() {
const [temperature, setTemperature] = useState('');

return (
<div>
<CelsiusInput temperature={temperature} onTemperatureChange={setTemperature} />
<FahrenheitInput temperature={temperature} onTemperatureChange={setTemperature} />
</div>
);
}

function CelsiusInput({ temperature, onTemperatureChange }) {


return (
<input
value={temperature}
onChange={(e) => onTemperatureChange(e.target.value)}
placeholder="Enter temperature in Celsius"
/>
);
}

function FahrenheitInput({ temperature, onTemperatureChange }) {


return (
<input
value={(temperature * 9/5) + 32}
onChange={(e) => onTemperatureChange((e.target.value - 32) * 5/9)}
placeholder="Enter temperature in Fahrenheit"
/>
);
}
The state temperature is lifted to the parent component, so both inputs can stay in sync.

5. Benefits of Lifting State Up


Ensures consistent and synchronized data across components.
Promotes better structure and reusability.
Helps in centralized state management for components that share logic or data.

6. Conclusion
Lifting state up is a fundamental concept in React that allows c
omponents to share and coordinate data effectively by moving the shared state to their
common ancestor. It helps maintain a clean, predictable, and unidirectional data flow across
the application.

5)Write a small Express API that can store and retrieve product information.

Express API to Store and Retrieve Product Informatio


Express.js is a lightweight web application framework for Node.js. It simplifies the process of
creating server-side APIs by providing routing and middleware capabilities.

1. Prerequisites
Node.js installed
Express installed using:

npm install express

2. Code: Simple Product API


const express = require('express');
const app = express();
const PORT = 3000;
// Middleware to parse JSON body
app.use(express.json());
// In-memory array to store product information
let products = [];
// Route to add a new product (POST)
app.post('/products', (req, res) => {
const product = req.body;
products.push(product);
res.status(201).send({ message: 'Product added successfully', product });
});
// Route to get all products (GET)
app.get('/products', (req, res) => {
res.send(products);
});
// Start the server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});

3. Sample Input & Output


POST /products
Request Body:
{
"id": 1,
"name": "Laptop",
"price": 50000
}

Response:

{
"message": "Product added successfully",
"product": {
"id": 1,
"name": "Laptop",
"price": 50000
}
}

GET /products

Response:

[
{
"id": 1,
"name": "Laptop",
"price": 50000
}
]
4. Explanation
app.post('/products'): Adds a new product using req.body.
app.get('/products'): Returns the list of stored products.
products[]: Acts as an in-memory storage array.

5. Conclusion
This simple Express API demonstrates how to store and retrieve product information using
POST and GET routes. It is ideal for beginners and aligns with the core principles of backend
development as per the BIS601 syllabus.

6)Compare GraphQL and REST. Highlight their strengths and limitations.

Comparison Between GraphQL and REST


GraphQL and REST are two popular approaches for designing web APIs. Both serve the
purpose of client-server communication but differ in design, flexibility, and performance.

1. REST (Representational State Transfer)


REST is an architectural style using standard HTTP methods (GET, POST, PUT, DELETE).
Resources are accessed via unique endpoints (e.g., /products, /users).
Data is usually returned in JSON format.

Strengths of REST:
Simplicity: Easy to understand and implement using standard HTTP.
Scalability: Works well with caching and load balancing.
Separation of Concerns: Each resource has its own endpoint and operation.

Limitations of REST:
Over-fetching or Under-fetching: Clients may receive more or less data than needed.
Multiple requests: Data from different resources often require multiple API calls.
Rigid structure: Changes in client needs may require new endpoints.

2. GraphQL (Graph Query Language)


GraphQL is a query language and runtime for APIs developed by Facebook.
Clients can request exact data they need in a single query.
All data is accessed through a single endpoint (e.g., /graphql).

Strengths of GraphQL:
Precise Data Fetching: Clients specify exactly what data they need.
Single Request: Can retrieve data from multiple resources in one call.
Strong Typing: Schema defines clear structure, enabling better validation and tooling.
Limitations of GraphQL:
Complexity: Requires a learning curve and schema setup.
Caching Issues: Difficult to cache queries compared to REST.
Overhead: For small apps, the benefits may not outweigh the complexity.

3. Comparison Table
Feature REST GraphQL
Endpoint Multiple (one per resource) Single (/graphql)
Data Fetching Fixed per endpoint Customizable per query
Over/Under Fetching Common issue Avoided
Learning Curve Low Moderate to high
Caching Easier with HTTP caching Harder without custom solutions
Development Speed Slower with frequent changes Faster for frontend needs

4. Conclusion
Both GraphQL and REST have their own strengths and limitations.
REST is ideal for simple, scalable APIs with fixed data structures.
GraphQL is suitable for complex applications that require flexibility and efficient data
retrieval.
Choosing between them depends on the project requirements, team skill level, and
performance needs.

7) How is a GraphQL schema structured? Provide an example.

A GraphQL schema defines the structure of data that clients can query from a server. It acts as
a contract between client and server, describing the types of data and relationships between
them.

1. Schema Structure Overview


A typical GraphQL schema is structured using the following elements:

a. Type Definitions (type)


Used to define custom object types like User, Product, etc.
Each type includes fields with their respective data types.

b. Query Type
Defines read operations clients can perform.
Acts as the entry point for fetching data.

c. Mutation Type (optional)


Defines write operations (e.g., create, update, delete data).
d. Scalars and Enums
Scalar types include Int, String, Boolean, Float, ID.
Enums define a set of named constants.

2. Example: Simple Product Schema


# Defining a custom object type
type Product {
id: ID!
name: String!
price: Float!
inStock: Boolean!
}

# Query type for reading data


type Query {
getProduct(id: ID!): Product
allProducts: [Product]
}

# Mutation type for writing data


type Mutation {
addProduct(name: String!, price: Float!, inStock: Boolean!): Product
}

3. Explanation
Product: A type with fields id, name, price, and inStock.
Query: Contains getProduct (fetch single product by ID) and allProducts (fetch all).
Mutation: Allows adding a new product using addProduct.

4. Features of a GraphQL Schema


Feature Description
Strongly typed Every field and argument has a specific type
Hierarchical structure Reflects how data can be nested or related
Single endpoint All operations go through one /graphql endpoint
Self-documenting Tools like GraphiQL can auto-generate docs

5. Conclusio
A GraphQL schema is the blueprint of the API. It clearly defines the types, queries, and
mutations available, making it easy for clients to understand and interact with the server. This
structured, type-safe design is one of the main advantages of using GraphQL over REST.
8)Write Express.js code that includes input validation and error handling.

Express.js Code with Input Validation and Error Handling


Express.js is a popular Node.js framework used to build RESTful APIs. For robust applications,
it's important to validate user input and handle errors gracefully.

1. Required Setup
Install the required packages:
npm install express express-validator
express: Framework to build API.
express-validator: Middleware for input validation.

2. Sample Code: Product API with Validation & Error Handling


const express = require('express');
const { body, validationResult } = require('express-validator');
const app = express();
app.use(express.json());
let products = [];
// Route to add product with validation
app.post('/products',
[
body('name').isString().withMessage('Name must be a string'),
body('price').isFloat({ gt: 0 }).withMessage('Price must be a positive number'),
body('inStock').isBoolean().withMessage('inStock must be a boolean')
],
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}

const product = req.body;


products.push(product);
res.status(201).send({ message: "Product added successfully", product });
}
);

// Global error handler (optional)


app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send({ error: 'Something went wrong!' });
});

// Start server
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});

3. Input Example
POST /products

{
"name": "Laptop",
"price": 55000,
"inStock": true
}

If any field is invalid, the server returns:

{
"errors": [
{ "msg": "Price must be a positive number", "param": "price", ... }
]
}

4. Key Features
Feature Description
express-validator Used to validate inputs before processing
validationResult() Collects and returns validation errors
Custom error messages Inform users of the exact validation failure
Centralized error handler Handles unexpected server-side errors gracefully

5. Conclusion
Input validation and error handling are essential for building secure and reliable Express.js
applications. The above example uses express-validator to ensure incoming data is valid and
provides meaningful error messages, aligning with the best practices covered in the BIS601
syllabus

You might also like