Thursday, April 16, 2026

Dynamic Import in Javascript

 

Dynamic Imports
If you need to load a function conditionally or on-demand (e.g., inside an if block or an event listener), use the import() function. This returns a Promise.

// Using .then()
import('./myFile.js').then((module) => {
  module.myFunction();
});

// Using async/await
const module = await import('./myFile.js');
module.myFunction();

React : Difference in creating a functional component with and without "function" keyword

Syntax Comparison

Method Syntax Example
Function Declarationfunction MyComponent(props) { ... }
Const Arrow Functionconst MyComponent = (props) => { ... }

Key Differences to Consider

IMP : CONTEXT IS NOT AVAILABE IN ARROW FUNCTIONS, HENCE YOU CANNOT USE "this" KEYWORD IN ARROW FUNCTIONS.
  • Hoisting: You can use a component defined with the function keyword before it appears in your code because it is "hoisted" to the top of the scope. Components defined with const must be defined before they are used.
  • Exporting: Using the function keyword allows you to use export default on the same line as the definition (e.g., export default function MyComponent() {}), which you cannot do with const.  
  •  "export default" cannot be combined with "const" in the same statement. They must be split on separate statements.   If you still want to use arrow syntax to declare a function, drop the "const" keyword and also DROP THE NAME OF FUNCTION. It becomes anonymous export, which is not a problem for default export, because the importing module anyway can use any convenient name to import a "export default".
  • TypeScript: If you use TypeScript, it is easier to apply the React.FC type to a const variable than to a standard function declaration.
  • Debugging: In older versions of React, function declarations provided clearer names in the React DevTools compared to anonymous arrow functions, though modern tooling largely fixes this for const variables as well. 

Which should you choose?

Most modern React developers prefer const arrow functions for consistency within the component (since hooks and event handlers inside are usually arrow functions), but using the function keyword is still a perfectly valid and standard way to write components.

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. 

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

Dynamic Import in Javascript

  Dynamic Imports If you need to load a function conditionally or on-demand (e.g., inside an  if  block or an event listener), use the  impo...