Thursday, April 16, 2026

React : Event handlers with parameters in functional components

In React, to pass parameters to an event handler, you must wrap the function call so that it is not executed immediately during the component's render phase. 

Primary Methods to Pass Parameters
  • Arrow Function Wrapper: The most common approach is to use an inline arrow function in the JSX attribute. This creates a new function that calls your handler with the specific arguments when the event occurs.
  • Function.bind(): You can use the method to pre-configure a function with specific arguments. The first argument to is the context (usually in functional components or in class components), followed by the parameters you want to pass.
  • Currying (High-Order Function): Define a function that returns another function. This is useful for passing parameters while keeping the JSX cleaner. 
Handling the Event Object

If you need both a custom parameter and the React SyntheticEvent object (e.g., to call ), you must pass the event explicitly when using an arrow function.
  • Arrow Function:
  • Bind: (The event object is automatically passed as the last argument) 
Performance Considerations

Creating functions inline (using arrow functions or ) generates a new function instance on every render. While usually fine for small applications, for performance-critical components (like large lists), consider using the
useCallback hook from React.dev to memoize the handler.




How to use useCallback hook to pass parameters

To use the useCallback hook with a parameter, you define the parameter in the function signature within the hook. This caches the function definition, ensuring that the same function instance is used between re-renders unless its dependencies change. 

Implementation with an ID Parameter

In this pattern, the useCallback hook defines how to handle the ID, while the actual ID is passed during the execution of that memoized function. 
import { useCallback } from 'react';

const MyComponent = ({ items }) => {
  // 1. Define the memoized handler with a parameter
  const handleItemClick = useCallback((id) => {
    console.log(`Clicked item with ID: ${id}`);
  }, []); // Empty dependency array means this function reference never changes

  return (
    <ul>
      {items.map((item) => (
        <li key={item.id}>
          {/* 2. Pass the parameter when the event occurs */}
          <button onClick={() => handleItemClick(item.id)}>
            Click {item.name}
          </button>
        </li>
      ))}
    </ul>
  );
};

Key Rules for useCallback

  • Parameter Location: Parameters are defined in the function passed to useCallback. They are not passed into the dependency array unless the logic inside the function relies on an external value that changes.
  • Dependency Array: Only include reactive values (props, state, or variables) that the function uses internally. If you don't use any external variables, use an empty array [].
  • Wrapper Still Required: In your JSX, you still need an inline arrow function (e.g., () => handleItemClick(id)) to actually call your memoized function with the specific ID. 

When is this actually useful?

Using useCallback with parameters is most effective when:
  • Passing to React.memo Children: If you pass this handler to a child component wrapped in React.memo, a stable function reference prevents the child from re-rendering unnecessarily.
  • Use in useEffect: If another useEffect or hook depends on your handler, memoizing it prevents that effect from running on every render. 






What about class components in React now ?

React still supports class-based components, but they are no longer recommended for new code. 


The current status of class components is as follows:
  • Supported, not Preferred: React has no immediate plans to remove class components, ensuring that legacy applications continue to function.
  • "Legacy" Status: Official documentation now categorizes class components under
    Legacy React APIs

    , emphasizing that function components with Hooks are the modern standard.
  • Missing Features: New React features, such as Server Components and certain optimizations, are designed specifically for function components and may not be available for classes.
  • Mandatory Use Case (Error Boundaries): Currently, you still must use a class component to create an
    Error Boundary

    , as there is no Hook equivalent for the or lifecycle methods yet.
  • Coexistence: You can freely mix class and function components within the same project. 
Why the Shift?

The React team transitioned to function components because classes were found to be more difficult for both humans and machines to optimize. Function components with Hooks allow for:
  • Better logic reuse without complex patterns like Higher-Order Components.
  • Cleaner code by eliminating the need for binding and constructors.
  • Improved performance through more efficient minification and "tree-shaking" during the build process. 



A Note on Error Boundary
An Error Boundary is a specialized React component that catches JavaScript errors anywhere in its child component tree, logs those errors, and displays a fallback UI instead of crashing the entire application. 

Key Features
  • Safety Net: Prevents the entire React component tree from unmounting due to an error in a single component.
  • Declarative: Unlike , which handles imperative code, error boundaries use React’s declarative nature to manage component-level crashes.
  • Granularity: They can be used at the top level (global error page) or wrapped around specific widgets to isolate failures. 
Implementation

To create an error boundary, you must use a class component that implements one or both of these lifecycle methods:
  1. : Used to update state so the next render shows a fallback UI (e.g., "Something went wrong").
  2. : Used to log error information to services like Sentry or Datadog for production monitoring. 
What They Do NOT Catch

Error boundaries do not catch errors for the following:
  • Event handlers (e.g., — use standard here instead).
  • Asynchronous code (e.g., , , or API calls).
  • Server-side rendering (SSR).
  • Errors thrown in the boundary itself (rather than its children). 
Modern Usage

While native error boundaries require class components, many developers use the react-error-boundary library. This library provides a reusable component and hooks like to handle errors in functional components more easily. 

What is a React Server Component ?

 A React Server Component (RSC) is a new type of React component that executes exclusively on the server (or at build time). Unlike traditional components, their code is never sent to the browser, which significantly reduces the JavaScript bundle size. 


Core Concepts
  • Zero Bundle Size: Because RSCs stay on the server, the libraries they use (like heavy Markdown parsers or database drivers) are not included in the client-side JavaScript bundle.
  • Direct Server Access: They can directly access server-side resources like databases, file systems, or internal microservices without needing an intermediate API layer.
  • Async by Nature: RSCs are often functions, allowing you to use standard syntax to fetch data directly inside the component body.
  • Stateless on the Client: They do not use client-side features like , , or browser APIs (e.g., , ).
Key Benefits
  • Performance: Faster initial page loads and improved Core Web Vitals, such as Largest Contentful Paint (LCP), because less JavaScript needs to be parsed and executed by the browser.
  • No Data Waterfalls: By fetching data on the server (closer to the data source), RSCs eliminate the "waterfall" effect where child components must wait for parent components to finish fetching data over the network.
  • Security: Sensitive information like API keys or database credentials remains securely on the server and is never exposed to the client.
Difference from Server-Side Rendering (SSR)

While both involve the server, they solve different problems:
  • SSR focuses on generating the initial HTML for a fast first view. The entire component tree still hydrates (becomes interactive) on the client, meaning all JavaScript is still sent to the browser.
  • RSC allows specific components to remain server-only. They send a serialized
    React Server Component Payload

    (not just HTML) that allows React to merge server-rendered UI into the client-side tree without losing client state.
When to Use Each
FeatureServer Component (RSC) Client Component
Data Fetching Yes (Directly from DB/API) No (Use hooks like )
Interactivity No (No click handlers) Yes (onClick, onChange, etc.)
State & Lifecycle No (, ) Yes
Backend Access Yes (File system, DB) No
Bundle Size Zero Contributes to JS bundle

In modern frameworks like Next.js (App Router), components are Server Components by default. To create a Client Component, you must add the directive at the top of the file. 


Comparing Next.js with Angular

 

FeatureNext.jsAngular
PhilosophyFlexible, Full-stackOpinionated, Frontend Framework
LanguageJavaScript/TypeScript (optional)TypeScript-first (Strict)
RenderingSSR, SSG, and ISR (Native)Primarily CSR (SSR requires setup)
RoutingFile-system based (Zero-config)Programmatic (Module-based)
Learning CurveGentle (if you know React)Steep (RxJS, DI, Modules)
State MgmtThird-party (Redux, Zustand)Built-in (Services, Signals)

AI Ecosystem 2026

Category Subcategory Tool / Framework Type Description Typical Use Cases
Cloud AI Platforms Full-stack AI Platform Azure AI Foundry Managed Platform End-to-end AI development (models, agents, deployment) Enterprise AI apps, copilots
Cloud AI Platforms Foundation Model Platform Amazon Bedrock Managed API Platform Access to multiple foundation models via API GenAI apps, chatbots
Cloud AI Platforms Agent SDK Platform Google Agent Development Kit SDK / Platform Tools to build agentic apps in Google ecosystem Multi-agent applications
Cloud AI Platforms LLM Agent SDK OpenAI Agents SDK SDK Build agent workflows using OpenAI models Assistants, automation
Orchestration Frameworks LLM App Framework LangChain Framework Chains, tools, and memory for LLM apps Chatbots, RAG systems
Orchestration Frameworks Graph-based Orchestration LangGraph Framework Stateful graph-based workflows Complex agent systems
Orchestration Frameworks Multi-agent Framework CrewAI Framework Role-based agent collaboration Task automation
Orchestration Frameworks Multi-agent Framework AutoGen Framework Conversational multi-agent workflows Autonomous systems
Orchestration Frameworks Agent Framework Microsoft Agent Framework Framework Enterprise-grade agent tooling Copilots, enterprise AI
Agent + RAG Frameworks RAG Framework Haystack Framework Search + retrieval pipelines QA systems
Agent + RAG Frameworks Agent Framework Semantic Kernel SDK / Framework Planning, memory, tool integration AI copilots
Model Runtime Local LLM Runtime Ollama Runtime Run LLMs locally Offline AI, testing
Low-Code / No-Code Visual Builder Flowise Low-code Tool Drag-and-drop LangChain UI Prototyping
Low-Code / No-Code AI App Platform Dify Platform Build & deploy AI apps visually Internal tools
Low-Code / No-Code Workflow Automation n8n Automation Tool Connect APIs & workflows Business automation
Data Layer Data Modeling Pydantic Library Data validation using Python types Structured outputs

Wednesday, April 15, 2026

Architectural Patterns of Agentic AI systems


The landscape of AI agents has shifted from simple "one-shot" prompting to complex agentic workflows. These architectures determine how an LLM thinks, uses tools, and corrects its own mistakes.

Here is a breakdown of the most prominent agentic architectures and the frameworks that power them.


1. ReAct (Reason + Act)

The Concept: ReAct is the "grandfather" of agentic design. It forces the LLM to generate a Thought (reasoning step) before performing an Action (calling a tool), and then process an Observation (result from the tool). This loop continues until the task is solved.

  • Architecture: Linear loop (Thought → Action → Observation).

  • Example Tool: LangChain (specifically the AgentExecutor). (NOTE: New version of LangChain is moved to graph-based architecture).

  • Best For: Simple, multi-step tasks where the next step depends entirely on the outcome of the current one.


2. Graph-Based Architecture

The Concept: Instead of a linear loop, graph architectures represent the agent’s logic as a Directed Acyclic Graph (DAG) or a cyclic graph. Each node is a function or an LLM call, and the edges define the flow based on conditional logic.

  • Architecture: State Machines (Nodes and Edges).

  • Example Tool: LangGraph.

  • Best For: Complex, "human-in-the-loop" workflows where you need fine-grained control, cycles (looping back to fix errors), and state management.


3. ReWOO (Reasoning Without Observation)

The Concept: Traditional ReAct agents can be slow because they wait for tool outputs before planning the next step. ReWOO decouples the reasoning from the execution. It looks at a prompt and creates a full plan of execution (with placeholders) all at once, then runs the tools in parallel.

  • Architecture: Planner → Worker → Solver.

  • Example Tool: LangGraph (can be used to implement ReWOO patterns) or CrewAI.

  • Best For: Reducing latency and token costs when tool calls are independent of each other.


4. Multi-Agent Systems (Role-Playing)

The Concept: Instead of one "super agent," you break the task down into specialized agents (e.g., a "Researcher," a "Writer," and a "Manager"). These agents communicate with each other to complete a goal.

  • Architecture: Hierarchical or Sequential collaboration.

  • Example Tool: Autogen (Microsoft) or CrewAI.

  • Best For: Large-scale projects like software development or comprehensive market research where different "personas" add value.


5. Plan-and-Execute

The Concept: Similar to ReWOO but more iterative. The agent first creates a long-term plan, executes the first few steps, and then re-plans based on the results. It is less rigid than ReWOO but more structured than ReAct.

  • Architecture: Planner → Executor → Re-planner.

  • Example Tool: BabyAGI or AutoGPT.

  • Best For: Open-ended goals where the path to the solution is highly uncertain.


Summary Comparison Table

ArchitecturePrimary LogicSpeedComplexityBest Framework
ReActIterative loopSlowLowLangChain
GraphState MachineVariableHighLangGraph
ReWOOPre-planned stepsFastMediumLangGraph / CrewAI
Multi-AgentCollaborationSlowHighAutogen / CrewAI





We are currently in a "Great Migration" period for agentic frameworks. As of 2026, the industry has largely moved away from "black-box" executors toward explicit, graph-based control.

Here is the re-confirmed, updated breakdown of these architectures based on the latest 2026 standards.


1. The Migration: LangChain → LangGraph

You are correct: LangChain has officially deprecated AgentExecutor (the legacy ReAct implementation). The community has shifted to LangGraph because the old ReAct loop was too hard to debug and impossible to "steer" mid-process.

Key Note: While "ReAct" still exists as a reasoning strategy, it is no longer the architecture in LangChain. It is now just one specific way to configure a Graph.


2. Updated Architectures (2026 Standards)

A. Graph Architecture (State Machines)

Instead of a hidden loop, every step is a Node and every transition is an Edge.

  • Current Standard: LangGraph.

  • The Change: LangChain 0.x used AgentExecutor (a pre-built loop). LangGraph 1.0+ requires you to define a StateGraph. You explicitly draw where the agent goes if a tool fails or if a human needs to approve a step.

  • Example: A customer support bot that cycles between "Search Documentation" and "Ask User for Clarification" until a confidence score is met.

B. Event-Driven & Conversational (The New AutoGen)

While graphs are rigid, Microsoft's AutoGen (v0.4+) has moved toward an Event-Driven Architecture.

  • Current Standard: AutoGen.

  • Mechanism: Agents act like microservices. They publish "events" (e.g., TaskCompletedEvent), and other agents subscribe to them.

  • Best For: Massive systems (thousands of agents) where a static graph would become a "spaghetti" mess of lines.

C. Role-Based Hierarchical (The CrewAI Way)

CrewAI has doubled down on the Manager-Worker architecture.

  • Current Standard: CrewAI.

  • Mechanism: It uses a "Process" (Sequential or Hierarchical). You define a Manager agent that acts as the orchestrator, delegating tasks to specific Roles.

  • Best For: Business processes where you need a clear "boss" agent to review work before finishing.

D. ReWOO (Reasoning Without Observation)

This remains the gold standard for low-latency and cost-saving.

  • Current Standard: Implemented as a specific template within LangGraph.

  • Mechanism: It breaks the task into a Planner, Worker, and Solver. The Planner creates a "blueprint" with placeholders (e.g., "Find the price of $X$ and $Y$"). Tools run in parallel, and the Solver fills in the blanks.

  • Status: It is now considered a "Design Pattern" rather than a standalone tool.


Quick Reference: What to use in 2026?

If you want...Use this ArchitectureLatest Tooling
Total Control / DebuggingGraph-BasedLangGraph
Autonomous CollaborationEvent-DrivenAutoGen 0.4+
Business WorkflowsRole-Based / HierarchicalCrewAI
Speed & Low CostReWOO (Planning)LangGraph Templates

Sunday, April 12, 2026

List Of Models/Algorithms in AI

Sr. No. Model Family (Learning Type) Model Type Model Name Popular Implementations / Models Use Cases
1Supervised LearningRegression / Linear ModelsLinear RegressionScikit-learn LinearRegressionHouse price prediction, forecasting
2Supervised LearningRegression / Linear ModelsLogistic RegressionScikit-learn LogisticRegressionSpam detection, credit scoring
3Supervised LearningTree-Based ModelsDecision TreeCART (Classification & Regression Trees)Loan approval, diagnosis
4Supervised LearningEnsemble (Bagging)Random ForestRandomForest (Scikit-learn)Fraud detection, risk modeling
5Supervised LearningEnsemble (Boosting)Gradient BoostingXGBoost, LightGBM, CatBoostRanking, fraud detection
6Supervised LearningDistance-Basedk-NNScikit-learn KNNRecommendation, similarity search
7Supervised LearningProbabilisticNaive BayesGaussianNB, MultinomialNBSpam filtering, NLP
8Supervised LearningMargin-BasedSVMLIBSVM, Scikit-learn SVMText classification, bioinformatics
9Supervised LearningNeural NetworksANNTensorFlow / PyTorch basic NNPrediction, pattern recognition
10Supervised LearningDeep LearningCNNResNet, VGG, EfficientNetImage recognition, medical imaging
11Supervised LearningDeep LearningRNN / LSTMSeq2Seq, LSTM (Keras/PyTorch)Speech, time-series
12Supervised LearningDeep LearningTransformersGPT, BERT, T5, LLaMAChatbots, search, translation
13Unsupervised LearningClusteringK-MeansScikit-learn KMeansCustomer segmentation
14Unsupervised LearningClusteringDBSCANScikit-learn DBSCANAnomaly detection
15Unsupervised LearningClusteringHierarchicalSciPy Hierarchical ClusteringTaxonomy, grouping
16Unsupervised LearningProbabilisticGMMScikit-learn GaussianMixtureSoft clustering
17Unsupervised LearningDimensionality ReductionPCAScikit-learn PCAVisualization, compression
18Unsupervised LearningDimensionality Reductiont-SNEsklearn / openTSNEEmbedding visualization
19Unsupervised LearningNeural NetworksAutoencodersTensorFlow / PyTorch AEAnomaly detection
20Unsupervised LearningAssociation RulesApriorimlxtend AprioriMarket basket analysis
21Semi-SupervisedHybridSelf-TrainingPseudo-labeling pipelinesMedical imaging
22Semi-SupervisedGraph-BasedLabel Propagationsklearn LabelPropagationSocial networks
23Semi-SupervisedNeural NetworksSemi-Supervised NNFixMatch, MixMatchNLP, speech
24Reinforcement LearningValue-BasedQ-LearningOpenAI Gym implementationsRobotics, games
25Reinforcement LearningDeep RLDQNDeepMind DQNGaming, control systems
26Reinforcement LearningPolicy-BasedPolicy GradientREINFORCERobotics
27Reinforcement LearningActor-CriticPPO / A2CStable-Baselines3Trading, optimization
28Optimization / EvolutionaryEvolutionaryGenetic AlgorithmsDEAP libraryScheduling, optimization
29Optimization / EvolutionarySwarmParticle Swarm OptimizationPySwarmsHyperparameter tuning
30Optimization / EvolutionarySwarmAnt Colony OptimizationACO algorithmsRouting, logistics
31Rule-Based / SymbolicExpert SystemsRule-Based SystemsDroolsBusiness rules
32Rule-Based / SymbolicKnowledge-BasedKnowledge GraphsNeo4j, RDF GraphsSearch, recommendations
33Ensemble LearningBaggingBaggingScikit-learn BaggingVariance reduction
34Ensemble LearningBoostingAdaBoostAdaBoost (sklearn)Classification improvement
35Ensemble LearningStackingStackingStackingClassifierHigh accuracy systems
36AI Systems (Hybrid)RAGRetrieval-Augmented GenerationLangChain, LlamaIndex + GPTEnterprise chatbots, QA
37AI Systems (Hybrid)Agentic PipelinesAI AgentsAutoGPT, CrewAI, LangGraphTask automation, research agents

Comparing features of LangGraph vs CrewAI

LangGraph Orchestration vs CrewAI Orchestration The following table compares LangGraph and CrewAI orchestration across their menta...