Wednesday, April 22, 2026

React : Event handlers with parameters in functional components

 Read with this post


In React, you cannot directly pass a parameter to a handler like because this executes the function immediately during rendering. Instead, you must pass a reference to a function that will execute later. 


1. Using Arrow Functions (Recommended)


The most common and readable way to pass parameters is by wrapping the handler call in an anonymous arrow function.
  • Standard Argument: .
  • With Event Object: If you also need the React event object (e.g., to call ), pass it explicitly through the arrow function:. 
2. Using the Method


You can use the JavaScript Function.prototype.bind() method to create a new function with the arguments pre-filled.
  • Syntax: .
  • Note: In class components, is required as the first argument to maintain context. In functional components, you can pass as the first argument. The React event object is automatically forwarded as the final argument. 
3. Using Data Attributes


For performance-critical lists, you can store data in
HTML data-* attributes

and retrieve them from the event object.
  • Implementation:
    • JSX: .
    • Handler: .
  • Advantage: Avoids creating a new function instance on every render, which is useful for very large lists. 
4. Function Currying


Currying involves creating a function that returns another function. This keeps your JSX cleaner.
  • Handler Definition: .
  • JSX Usage:
MethodPrimary Use Case Performance Impact
Arrow Function Most common, standard applications Minimal (creates new function on render)
.bind() Class components Minimal (same as arrow function)
Data Attributes High-performance lists Best (uses a single function reference)
Currying Clean JSX syntax Minimal (same as arrow function)


Caution: Creating functions inside the method (via arrow functions or ) can sometimes cause unnecessary re-renders in child components that use React.memo. 



CSS Flex

 In CSS, Flexbox (Flexible Box Layout) is a one-dimensional layout model designed for arranging elements in rows or columns. It allows child elements (flex items) to "flex" their sizes—growing to fill unused space or shrinking to fit smaller containers—without the need for complex positioning or floats. 


The term "flex" is commonly used in two ways in CSS: 

1. The Property

Applying to a parent element (the flex container) automatically makes all its direct children flex items.
  • Main Axis & Cross Axis: Items are laid out along a main axis (horizontal by default) and a perpendicular cross axis.
  • Container Control: You can control the container using properties like (main-axis alignment) and (cross-axis alignment). 
2. The Shorthand Property

Used on individual flex items, the property is a shorthand for three sub-properties that determine how that specific item occupies space:
  • : Defines how much an item should grow relative to its siblings if there is extra space.
  • : Defines how much an item should shrink if the container is too small to fit everything.
  • : Defines the initial size of the item before any growing or shrinking occurs. 
Common Shorthand Values:
  • : Equivalent to . The item will grow and shrink to fill available space equally with other items marked .
  • : Equivalent to . The item grows and shrinks based on its initial content size.
  • : Equivalent to . The item becomes fully inflexible, neither growing nor shrinking. 
Key Benefits
  • Responsiveness: Items adjust dynamically to different screen sizes and orientations.
  • Alignment: Easily center content vertically and horizontally with a few lines of code.
  • Order: You can change the visual order of items using the property without changing the underlying HTML. 

CSS : Elements that collapse to 0px

 

1. Elements that collapse to 0px

In CSS, almost any Block-level or Inline-block element will collapse to 0px height if it contains no children, no text, and no fixed dimensions.
Common examples include:
  • Containers: <div>, <section>, <article>, <main>, <header>, <footer>.
  • Layout Elements: <span> (if set to display: block or inline-block), <aside>, <nav>.
  • Lists: <ul> and <ol> (if they have no <li> children).
  • Flex/Grid Items: If a container is display: flex, its children will still collapse unless they have content or a specific flex-basis.
Note: Elements like <img>, <input>, or <button> are "Replaced Elements." They usually have default browser dimensions even when "empty."

2. Attributes that require a Parent Reference

The "100% of auto is 0" rule applies to several CSS properties. If the parent’s size is determined by its own content (dynamic), these attributes will fail to calculate:
  • height: As you discovered, 100% height requires the parent to have a fixed height (px, vh, etc.) or also be a percentage child of a fixed-height container.
  • min-height / max-height: Percentage values here follow the exact same rule as height.
  • margin (Top/Bottom): If you use percentages for vertical margins, they are actually calculated based on the width of the parent, not the height (a common CSS "gotcha").
  • padding (Top/Bottom): Like margins, vertical padding percentages are also based on the parent's width.
  • top / bottom: When using position: absolute, these percentages relate to the height of the nearest "positioned" (relative/absolute) ancestor.
  • flex-basis: If set to a percentage, it depends on the parent flex container’s main axis size.

The Logic Tip

In CSS, Width is "infinite" (it defaults to 100% of the screen/parent), but Height is "finite" (it defaults to 0 and grows with content). This is why width: 100% almost always works, while height: 100% usually feels "broken."


Inline styles in React in jsx

 The attribute declaration and naming changes in jsx. 


HTML : 

<table style="border-collapse : collapse" > </table>


JSX: 

<table style={{ borderCollapse : "collapse" }} > </table>

SSR, SSG, ISR, RSC, CSR

These terms represent different ways a web server and browser "collaborate" to turn your code into a visible page.

๐Ÿ›️ Static Site Generation (SSG)

The page is built once at build time (when you run npm run build).
  • How it works: The server generates HTML files for every page before the site goes live.
  • Pros: Blazing fast; works great with CDNs; excellent for SEO.
  • Best for: Blogs, documentation, marketing sites.

๐Ÿ”„ Incremental Static Regeneration (ISR)

A "hybrid" that allows you to update static pages after the site is live, without a full rebuild.
  • How it works: You set a "revalidate" timer (e.g., 60 seconds). If a user visits after that time, the server generates a fresh version in the background.
  • Pros: Fast like SSG, but keeps data fresh.
  • Best for: E-commerce product pages, news feeds.

๐ŸŒ Server-Side Rendering (SSR)

The page is generated on the server every time a user requests it.
  • How it works: When a user hits a URL, the server fetches data, builds the HTML, and sends it back immediately.
  • Pros: Real-time data; highly personalized (e.g., user profiles).
  • Best for: Social media feeds, banking dashboards.

⚡ React Server Components (RSC)

A modern approach (standard in Next.js App Router) where components stay on the server.
  • How it works: The component logic runs only on the server. Only the result (not the JavaScript code for the component) is sent to the browser.
  • Pros: Drastically reduces the amount of JavaScript sent to the client; faster loading.
  • Best for: Modern Next.js apps using the /app directory.

๐Ÿ’ป Client-Side Rendering (CSR)

The browser does all the work.
  • How it works: The server sends a nearly empty HTML file and a large JavaScript bundle. The browser then executes the JS to "paint" the UI.
  • Pros: Smooth "app-like" transitions after the initial load.
  • Best for: Interactive tools, SaaS apps where SEO doesn't matter.

๐Ÿ’ก The Key Difference:
It's all about when and where the HTML is created:
  • SSG: At build time (Server).
  • SSR: At request time (Server).
  • CSR: At runtime (Browser).

Compare: JavaScript reduce vs C# Aggregate vs Java reduce

1. Signatures

JavaScript (Array.reduce)


arr.reduce((accumulator, currentValue, index, array) => { ... }, initialValue)

C# (LINQ Aggregate)


collection.Aggregate(
    seed,
    (acc, current) => ...
)

Optional overload:


collection.Aggregate(
    seed,
    (acc, current) => ...,
    resultSelector
)

Java (Streams reduce)


stream.reduce(identity, (acc, current) -> ...)

Optional:


stream.reduce((acc, current) -> ...)
---

2. Parameter Comparison

FeatureJavaScriptC#Java
AccumulatorYesYesYes
Current valueYesYesYes
IndexYesNoNo
Original arrayYesNoNo
Initial valueOptionalRequiredOptional
---

3. Example: Sum

JavaScript


arr.reduce((acc, x) => acc + x, 0);

C#


arr.Aggregate(0, (acc, x) => acc + x);

Java


Arrays.stream(arr)
      .reduce(0, (acc, x) -> acc + x);
---

4. Example: Average

JavaScript


arr.reduce((acc, x, i, arr) => acc + x / arr.length, 0);

C#


arr.Average();

Manual:


arr.Aggregate(0, (acc, x) => acc + x) / arr.Count();

Java


Arrays.stream(arr).average().getAsDouble();

Manual:


Arrays.stream(arr)
      .reduce(0, (acc, x) -> acc + x) / arr.length;
---

5. Object Accumulator Example

JavaScript


arr.reduce((acc, x) => {
  acc.sum += x;
  acc.count++;
  return acc;
}, { sum: 0, count: 0 });

C#


var result = arr.Aggregate(
    new { Sum = 0, Count = 0 },
    (acc, x) => new { Sum = acc.Sum + x, Count = acc.Count + 1 }
);

Java


var result = Arrays.stream(arr)
    .reduce(
        new int[]{0,0},
        (acc, x) -> new int[]{acc[0] + x, acc[1] + 1},
        (a, b) -> new int[]{a[0] + b[0], a[1] + b[1]}
    );
---

6. Key Differences

  • JavaScript provides extra parameters (index and array).
  • C# and Java keep the API minimal and functional.
  • C# requires an initial value (seed), while JavaScript and Java do not.
  • Java supports parallel reduction (requires combiner logic).
  • C# and Java encourage immutability in reduce operations.
---

7. Mental Model


JavaScript → flexible (extra context available)
C#        → structured (LINQ-based aggregation)
Java      → functional + parallel-ready reduction
---

8. Final Mapping


JS reduce      = flexible loop with extra context
C# Aggregate   = structured accumulation
Java reduce    = functional + parallel-safe reduction
---

9. Practical Advice

  • Use reduce/aggregate for combining values.
  • Use map/Select for transformation instead.
  • Prefer built-in helpers when available:
    • C# → Sum(), Average()
    • Java → sum(), average()

Arrays & Functional Pipelines Across JavaScript, C#, and Java

Arrays & Functional Pipelines Across JavaScript, C#, and Java

๐Ÿง  1. Core Philosophy

LanguageNature of Arrays
JavaScriptDynamic, flexible, loosely typed
C#Fixed-size, strongly typed
JavaFixed-size, strongly typed

Real-world usage:

  • JavaScript → flexible pipelines
  • C#/Java → prefer collections (List, ArrayList)
---

๐Ÿ“ฆ 2. Collections Overview

C# Collections

Non-Generic (Legacy)

ClassGeneric Version?
ArrayListNo
HashtableNo
StackNo
QueueNo

Generic (Modern)

Class
List<T>
Dictionary<K,V>
HashSet<T>
Queue<T>
Stack<T>
LinkedList<T>
SortedList<K,V>
SortedDictionary<K,V>
---

Java Collections

CategoryExamples
ListArrayList, LinkedList
SetHashSet, TreeSet
MapHashMap, TreeMap
QueuePriorityQueue, Deque
---

JavaScript Collections

  • Array
  • Map
  • Set
  • WeakMap
  • WeakSet
---

๐Ÿ” 3. Functional Pipeline Mapping

ConceptJavaScriptC# (LINQ)Java (Streams)
TransformmapSelectmap
FilterfilterWherefilter
ReducereduceAggregatereduce
FlatMapflatMapSelectManyflatMap
FindfindFirstfindFirst
AnysomeAnyanyMatch
AlleveryAllallMatch
ContainsincludesContainscontains
SortsortOrderBysorted
---

⚙️ 4. JavaScript Array Methods

Mutating

  • push, pop
  • shift, unshift
  • splice
  • sort, reverse

Non-Mutating

  • map
  • filter
  • slice
  • concat
  • flat, flatMap

Value Returning

  • reduce
  • find
  • includes
  • some, every
---

๐Ÿ“ค 5. Return Types

Method TypeReturns
map/filter/flatNew array
reduceSingle value
findElement
some/everyBoolean
push/unshiftNew length
pop/shiftRemoved element
spliceRemoved elements (array)
sort/reverseMutated array
---

๐Ÿ”ฅ 6. map vs reduce

map

[1,2,3].map(x => x * 2) → [2,4,6]

reduce

[1,2,3].reduce((acc,x) => acc+x,0) → 6

Rule: map = transform, reduce = combine

---

๐Ÿงฎ 7. reduce Explained

With initial value

arr.reduce((acc,x)=>acc+x,0)

Without initial value

arr.reduce((a,b)=>a+b)

Best practice: Always provide initial value

---

๐Ÿ”€ 8. flat vs flatMap

flat

[1,[2,3]].flat() → [1,2,3]

flatMap

[1,2,3].flatMap(x => [x,x*2]) → [1,2,2,4,3,6]
---

๐Ÿ” 9. Equivalent in C# and Java

C#


arr.Select(...)
arr.Where(...)
arr.Aggregate(...)
arr.SelectMany(...)

Java


stream.map(...)
stream.filter(...)
stream.reduce(...)
stream.flatMap(...)
---

๐Ÿ”„ 10. Iterator vs Enumerator

ConceptJavaC#
PatternIteratorEnumerator
MovehasNext()MoveNext()
Valuenext()Current
---

⚡ 11. Performance


for loop   → fastest
foreach    → cleaner
stream     → readable but overhead
---

๐ŸŒŠ 12. Functional vs Streaming

  • Functional: map, filter, reduce
  • Streaming: file/network streams
---

๐Ÿ“ก 13. Kafka & Arrays


C# Object → JSON/Avro → Kafka → Java Object
---

๐Ÿงพ 14. Avro

  • Binary format
  • Schema-based
  • Efficient
---

๐Ÿง  Final Mental Model


Arrays → Data
map    → Transform
filter → Select
flatMap→ Expand
reduce → Combine
---

๐Ÿ”š Key Takeaways

  • Arrays are data pipelines
  • flatMap / SelectMany is critical
  • reduce is powerful but tricky
  • Prefer functional style
  • Kafka uses serialized data

React : Event handlers with parameters in functional components

 Read with  this post In React, you cannot directly pass a parameter to a handler like because this executes the function immediately durin...