Module 2 -Node JS Rest API-
Module 2 -Node JS Rest API-
A massive industry relevant skill enhancement initiative for the Youth of Tamil Nadu.
WEEK 1 – PROGRAM ORIENTATION
● React JS is an adaptable JavaScript library for creating user interfaces, especially for building single-page
applications.’
● It was initially developed and is still maintained by Facebook.
● React's ability to dynamically update and render data without requiring full-page reloads enhances the performance
and responsiveness of web applications.
● An example for this can be search bar of an amazon application, where, when user types in the search field, React can
update the search results in real time by dynamically fetching and rendering matching products without reloading the
entire page.
● This can be achieved using onChange events, useStates of react.
Features of React
● Virtual DOM:
React uses a lightweight copy of the real DOM to detect and apply only the necessary changes, improving performance.
● One-way Data Binding:
Data flows from parent to child components. Children can't directly change parent data, ensuring better control and stability.
Features of React
● Performance:
React updates only what's needed, making apps faster. Its component-based structure enhances efficiency and
scalability.
● Extension:
React supports extensions like Redux (state management) and React Native (mobile development).
● Simplicity:
Component-based architecture and JSX make development clean, modular, and easy to debug.
● Components:
Reusable, self-contained units that handle their own logic and UI, making development faster and more
organized.
.
ReactJs Architecture
ReactJs Architecture
● Component-Based Architecture:
React builds UIs using reusable, self-contained components that manage their
own logic and state.
● JSX:
A syntax extension that allows writing HTML-like code in JavaScript,
making UI code more readable and dynamic.
● Virtual DOM:
React creates a virtual copy of the real DOM. When state changes, it
compares the new virtual DOM with the previous one and updates only the
changed parts in the real DOM, improving performance.
● Types of Components:
Functional Components: Defined using functions. Use Hooks like useState
and useEffect for state and side effects.
● State Management:
Components manage their own state. Hooks like useState and useEffect help handle state and side effects like API calls.
● One-Way Data Binding:
Data flows from parent to child via props. Props are read-only, ensuring predictable behavior.
● Example:
function Apple(props) {
return <p>{props.message}</p>;
}
function Fruit() {
return <Apple message="Apple is rich in Vitamin C" />;
}
JSX is JavaScript XML which is the syntax extension for JavaScript that look similar to HTML
but is the react library which allows to to write HTML structures along with JavaScript code
basically combining both the languages capabilities. This JSX is transpiled into the regular
JavaScript language using the Babel tools that helps browsers to interpret JSX.
The new component can be created and imported to app.js to host the custom
component, for example lets create new js file with custom code and import it
from app.js file:
Open the browser after npm start,
Understanding props and State
The Props and States in react are useful for managing the passage of data from
components that helps in building dynamic and interactive User Interfaces.
Props:
● Props in react are short form for properties which are used to pass data from
parent component to child component
● These props are read only in which, the child component cannot change these
properties received from parent component. That is, props are immutable.
● Generally the props are passed from parent component in the way of adding
attributes to the component’s tag in JSX, which the child component can access
using ‘this.props’ or directly as function parameters.
✅ ProfileCard with Props Example
function NameForm() {
const [name, setName] = useState("");
return (
<div>
<input
type="text"
placeholder="Please enter your name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<p>Your name is: {name}</p>
</div>
);
}
✅ Example:
2️⃣ render()
✅ What it does:
✅ Example:
render() {
return <h1>Count: {this.state.count}</h1>;
}
3
3️⃣ componentDidMount()
✅ What it does:
✅ Example:
componentDidMount() {
console.log("Component mounted");
fetchData();
}
✅ Example:
shouldComponentUpdate(nextProps, nextState) {
return nextState.count !== this.state.count;
}
5️⃣ getDerivedStateFromProps(props, state)
✅ What it does:
● Static method
● Runs before render during mount and update
● Used to sync state with props
✅ Example:
✅ Example:
componentDidUpdate(prevProps, prevState) {
if (prevState.count !== this.state.count) {
console.log("Count updated:", this.state.count);
}
}
7
7️⃣ getSnapshotBeforeUpdate(prevProps, prevState)
✅ What it does:
✅ Example:
getSnapshotBeforeUpdate(prevProps, prevState) {
if (prevProps.message !== this.props.message) {
return this.divRef.scrollTop;
}
return null;
}
8️⃣ componentWillUnmount()
✅ What it does:
✅ Example:
componentWillUnmount() {
console.log("Component will be removed");
clearInterval(this.timer);
}
Conditional Rendering and Event Handling
🔍 What is Conditional Rendering?
Conditional rendering means showing different UI elements depending on a condition or application state. It’s
useful for:
function MyGreetings(props) {
const isLoggedIn = props.isLoggedIn;
return (
<div>
{isLoggedIn ? <h1>Hey, Welcome back!</h1> : <h1>How are you?</h1>}
</div>
);
}
export default MyGreetings;
▶️Using Logical && (Short-circuit evaluation)
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
return <div>{isLoggedIn && <h1>Hey, Welcome back!</h1>}</div>;
}
export default Greeting;
● Event handling in React is similar to how you handle events in JavaScript, with
a few syntactical differences.
● In React, events are named using camelCase, and you pass event handlers as
functions rather than strings. There are few basic principles that align with
react’s few basic principles that align with its component-based architecture
Synthetic event system, Naming conventions, Passing event handlers as props and
Inline function and component methods
->The synthetic event system that ensures events behave consistently across
different browsers.
🔹 Synthetic Event Example
function InputLogger() {
function handleInputChange(event) {
console.log("Synthetic:", event);
console.log("Native:", event.nativeEvent);
}
return <input type="text" onChange={handleInputChange} />;
}
🔹 Naming Convention
● Handlers usually follow handleEventName format (e.g., handleClick)
return (
<div>
<button onClick={handleClick}>Click me</button>
<p>Clicked {count} times</p>
</div>
);
}
Passing Arguments to Event Handlers
Passing arguments to event handlers in React is a common requirement when you need to
perform actions on specific data associated with an event. For example, deleting or editing a
resource.
● Use event.preventDefault() in your event handlers when you need to stop the browser from
performing default actions, like submitting a form.
● For example, to prevent the browser from refreshing when a form is submitted, or prevent any
other default behavior, pass the event parameter into the function handling the onSubmit
event, then use that event to call a preventDefault function.
Example app3.js:
import React, { useState } from "react";
function FormComponent() {
const [inputvalue, setInputValue] = useState("");
const handleInputChange = (event) => {
setInputvalue(event.target.value);
};
const handleSubmit = (event) => {
event. preventDefault();
console.log("Form submitted with input:", inputvalue);
placeholder="Enter something ... "
setInputValue("");
/>
};
<button
return (
type="submit">Submit</button>
<form onSubmit={handleSubmit}>
</form>
<input
);
type="text"
}
value={inputValue}
export default FormComponent;
onchange={ handleInputChange}
4. Clean Up Event Listeners:
If we use event listeners in useEffect, always return a cleanup
function to remove the event listener. Otherwise, it'll cause memory
leaks.
Example without cleaning functions:
import React, { usestate, useEffect } from "react";
function Timer() {
const [count, setCount] = usestate(0);
useEffect(() => {
const intervalId = setInterval(() => {
setCount((prevCount) => prevCount +1);
}, 1000);
}, []);
return <div>Count: {count}</div>;
}
export default Timer;
Using cleanup function:
import React, { usestate, useEffect } from "react";
function Timer() {
const [count, setCount] = usestate(0);
useEffect(() => {
const intervalId = setInterval (() => {
setCount((prevCount) => prevCount + 1);
}, 1000);
return () => {
//here is the cleanup happening
clearInterval(intervalId);
}, []);
return <div>Count: {count}</div>;
}
export default Timer;
5. Event Propagation
Use event.stopPropagation() to stop bubbling up to parent handlers.
const handleClick = (e) => {
e.stopPropagation();
alert("Child clicked!");
};
In React, state updates and component re-renders are foundational concepts. When
state changes, React re-renders the component to reflect the new data in the UI.
📦 What is State?
● State represents dynamic data that can change over time within a
component.
● Updating state triggers a re-render to keep the UI in sync with the
internal data.
● In functional components, state is managed with the useState hook.
● In class components, it's managed using this.setState.
⚙️Functional Component with useState
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
export default Counter;
function DoubleCounter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={incrementTwice}>Increment Twice</button>
</div>
);
}
export default DoubleCounter;
React batches the updates when they're in the same event handler.
Using prev => prev + 1 ensures each update is based on the latest value.
Re-Renders in React
● When a component’s state or props change, React schedules a re-render. This re-
render process is top-down, meaning:
● A parent component's re-render causes its child components to re-render — even
if their props haven’t changed.
✅ Optimized Version:
import React, { useState } from "react";
function Parent() {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount(count + 1)}>
Increment Parent Count
</button>
<Child count={count} />
</div>
);
}
const Child = React.memo(({ count }) => {
console.log("Child re-rendered");
return <p>Parent Count: {count}</p>;
});
export default Parent;
⏳ 2. Asynchronous Operations
❖ Operations like setTimeout, fetch, and Promise-based tasks are asynchronous.
❖ These are non-blocking, so they don’t halt the main thread.
❖ Instead, they are handled by the browser's Web APIs.
🌐 3. Web APIs
○ If the Call Stack is empty, it first processes all tasks in the Microtask Queue.
● Microtasks (like .then, .catch, async/await) are prioritized over regular tasks.
Memoization for Performance Optimization
Memoization is a performance optimization technique where the results of expensive function calls are
cached and reused if the same inputs occur again. This prevents unnecessary computations and re-renders,
improving performance in React applications.
✅ Example – Child.js
import React, { PureComponent } from "react";
class Child extends PureComponent {
render()
<div>
{/* Display the color prop */}
<h2>Child Component - Color: {this.props.color}</h2>
</div>
);
}
}
export default Child;
✅ Example – Parent.js
import React, { Component } from "react";
import Child from "./Child";
class Parent extends React.Component {
constructor(props) {
super(props);
this.state={ color: "pink" };
}
changeColor = () => {
this.setState((prevState) => {
return { color: prevState.color ==="red" ? "blue" : "red" };
});
render() {
console.log("Parent render");
return (
<div className="App">
<button onclick={this.changeColor}>Change Color</button>
<h2>Current Color: {this.state.color}</h2>
<Child color={this.state.color} />
</div>
);
}
}
export default Parent;
2. useMemo: Memoizing Expensive Computations
The useMemo hook memoizes the result of a function and recomputes it only when its dependencies
change. It's especially useful when an operation is expensive and shouldn't be recalculated on every render.
Example – memozation2.js
function OptimizedCalculationComponent() {
const [count, setCount] = useState(0); const [text, setText] = useState("");
const calculateDouble = (number) => {
console.log("Performing an expensive calculation...");
return number * 2;
};
const memoizedResult = useMemo(() => {
return calculateDouble(count);
}, [count]);
return (
<div>
<button onClick={() => setCount(count + 1)}>Increment Count</button>
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
/>
<p>Count: {count}</p>
<p>Memoized Result: {memoizedResult}</p>
</div>
);
}
export default OptimizedCalculationComponent;
3. useCallback: Memoizing Functions
The useCallback hook memoizes function references, preventing them from being recreated on every render
unless their dependencies change. This is especially useful when passing functions to child components, so
React.memo can effectively prevent re-renders .
File – memoization.js
import React, { useState, useCallback } from "react";
function Parent() {
const [count, setCount] = useState(0);
const [text, setText] = useState("");
const increment = useCallback(() => { setCount(count + 1);
}, [count]);
return(
<div>
<button onclick={increment}>Increment</button>
<Child count={count} />
<input value={text} onChange={(e) => setText(e.target.value)} />
</div>
);
}
const Child = React.memo(({ count }) => {
console.log("Child re-rendered");
return <p>Count: {count}</p>;
});
export default Parent;
4. React.memo: Optimizing Functional Components
React.memo is a Higher-Order Component that prevents re-rendering of functional
components if their props haven’t changed.
File – memo.js