<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chandralekha S on Medium]]></title>
        <description><![CDATA[Stories by Chandralekha S on Medium]]></description>
        <link>https://medium.com/@chandralekha-selvam?source=rss-7f0675f5d3d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*5yCMLuhePFbD_FrH.jpg</url>
            <title>Stories by Chandralekha S on Medium</title>
            <link>https://medium.com/@chandralekha-selvam?source=rss-7f0675f5d3d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 05:44:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chandralekha-selvam/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[JSON vs TOON]]></title>
            <link>https://medium.com/@chandralekha-selvam/json-vs-toon-b71353f1a4d4?source=rss-7f0675f5d3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b71353f1a4d4</guid>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[toon]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Chandralekha S]]></dc:creator>
            <pubDate>Tue, 11 Nov 2025 18:20:11 GMT</pubDate>
            <atom:updated>2025-11-11T18:20:11.202Z</atom:updated>
            <content:encoded><![CDATA[<p>TOON (Token-Oriented Object Notation) is a compact, human-readable way to send structured data — especially to LLMs — using fewer tokens than JSON on common “rows of objects” data. Keep JSON for APIs/programming. Use TOON as a <em>prompt transport</em> to cut token costs, speed up responses, and add light structure the model can follow.</p><h3>What is TOON?</h3><p>Think of JSON as a full paragraph with punctuation. TOON is the same information written in a tight, column-style list (like “CSV with hierarchy”), which LLMs can read with fewer tokens. TOON declares fields once and then streams rows — great for “arrays of objects” such as products, events, logs, users. It’s indentation-based (like YAML), tabular for arrays (like CSV), and optimized for LLM tokenization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MXxdmtPLnUJ5-s9UrctdWQ.gif" /><figcaption>JSON vs TOON example</figcaption></figure><p>Typical savings are cited ~30–60% fewer tokens vs formatted JSON on uniform arrays — which can mean faster prompts and lower cost. <a href="https://github.com/toon-format/toon#benchmarks">Benchmarks</a> shared publicly show substantial token reductions in practical runs.</p><p>JSON</p><pre>{<br>  &quot;users&quot;: [<br>    { &quot;id&quot;: 1, &quot;name&quot;: &quot;Alice&quot;, &quot;role&quot;: &quot;admin&quot; },<br>    { &quot;id&quot;: 2, &quot;name&quot;: &quot;Bob&quot;,   &quot;role&quot;: &quot;user&quot;  }<br>  ]<br>}</pre><p>TOON</p><pre>users[2]{id,name,role}:<br>  1,Alice,admin<br>  2,Bob,user</pre><blockquote>Notice how TOON declares the <strong>headers once</strong> and lists the <strong>rows</strong> — less repeated punctuation/keys.<br>JSON repeats keys (&quot;id&quot;, &quot;name&quot;, &quot;role&quot;) and punctuation.<br>TOON states the schema once: [2]{id,name,role} → then streams rows.<br>Result: fewer tokens to send the same facts.</blockquote><p>When to use TOON<br><strong>Great for:<br></strong>✅ Arrays of similar objects: products, events, logs, telemetry, leaderboards.<br>✅ LLM prompts where token cost &amp; latency matter: analytics, RAG attributes, summaries.<br><strong>Not ideal<br></strong>❌ Deeply nested or irregular data: JSON can be smaller/clearer there.<br>❌ Purely tabular CSV cases: CSV might be smallest; TOON adds minimal structure overhead by design.</p><p>Migration: Add TOON <em>without</em> breaking your stack</p><blockquote><strong>Principle:</strong> Keep JSON for <strong>APIs, storage, program logic</strong>. Add a <strong>thin TOON adapter</strong> only where you assemble <strong>LLM prompts</strong>.</blockquote><p>In your UI <br> → <strong>Keep your app state in JSON</strong> as usual.<br> → When you call an LLM, <strong>convert</strong> the JSON slice to TOON right before sending.<br> → Log <strong>both</strong> JSON size and TOON size during experiments to quantify wins.</p><pre>// npm i @toon-format/toon<br>import { encode } from &#39;@toon-format/toon&#39;;<br><br>const data = {<br>  users: [<br>    { id: 1, name: &#39;Alice&#39;, role: &#39;admin&#39; },<br>    { id: 2, name: &#39;Bob&#39;,   role: &#39;user&#39;  },<br>  ],<br>};<br><br>// Convert only for the LLM prompt:<br>const toon = encode(data);<br>/*<br>users[2]{id,name,role}:<br>  1,Alice,admin<br>  2,Bob,user<br>*/</pre><p>In your backend make these changes<br> → <strong>Add a prompt-builder module</strong> that accepts JSON and returns TOON.<br> → Use the <strong>CLI</strong> in pipelines for batch jobs and to print <strong>token savings</strong> stats.<br> → Put <strong>feature flags</strong> around TOON usage so you can fall back to JSON instantly.</p><pre># Convert JSON → TOON, show estimated token savings<br>npx @toon-format/cli data.json --stats -o data.toon<br><br># Convert TOON → JSON (debug or interop)<br>npx @toon-format/cli data.toon -o data.json</pre><p>so how to <em>use</em> TOON in prompts??<br> → <strong>System/Tool instructions:</strong> “You will receive TOON. Respect declared counts and fields.”<br> → <strong>Insert TOON block:</strong> the encoded string from your adapter.<br> → <strong>Ask schema-aware questions:</strong> “For each user, compute … return JSON with fields {dept, avgSalary}.”</p><p>This leverages TOON’s “guardrails” (declared counts/headers) to reduce hallucinated fields and improve extraction reliability.</p><p>Pros:<br>✅ <strong>Token &amp; latency savings</strong> for uniform arrays (typ. 30–60%).<br>✅ <strong>LLM-friendly structure:</strong> explicit lengths/headers; easier to validate in your tool.<br>✅ <strong>Human-readable:</strong> like CSV+YAML; easier to eyeball large lists<br>Cons<br>❌ <strong>New format:</strong> teammates &amp; linters won’t know it yet; add small docs.<br>❌ <strong>Tooling maturity:</strong> JSON remains king for APIs, schemas, IDE hints. Use TOON only at the <strong>prompt boundary</strong>.<br>❌ <strong>Not universal win:</strong> for deep/irregular structures, JSON may still be smaller/clearer.</p><p>consider this s<strong>cenario:</strong> You want an LLM to compute “average price per category” from a product list.</p><p><strong>JSON you already have</strong></p><pre>{<br>  &quot;products&quot;: [<br>    { &quot;id&quot;: 1, &quot;name&quot;: &quot;Pen&quot;,   &quot;category&quot;: &quot;Office&quot;, &quot;price&quot;: 10.5 },<br>    { &quot;id&quot;: 2, &quot;name&quot;: &quot;Paper&quot;, &quot;category&quot;: &quot;Office&quot;, &quot;price&quot;: 2.0  },<br>    { &quot;id&quot;: 3, &quot;name&quot;: &quot;Bowl&quot;,  &quot;category&quot;: &quot;Home&quot;,   &quot;price&quot;: 12.0 }<br>  ]<br>}</pre><p><strong>TOON you send to the model</strong></p><pre>products[3]{id,name,category,price}:<br>  1,Pen,Office,10.5<br>  2,Paper,Office,2.0<br>  3,Bowl,Home,12.0</pre><p><strong>so here in the above TOON we have<br></strong>☑ <strong>Headers</strong> ({id,name,category,price}) reduce repeated keys.<br>☑ <strong>Row stream</strong> shows values compactly.<br>☑ <strong>products[3]</strong> helps the model expect exactly 3 rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8TY1Nji9SmUC7cffxzwAHQ.png" /><figcaption>JSON ↔︎ TOON mapping</figcaption></figure><p>Ok then what will change in your code?</p><p><strong>None for your APIs/storage.</strong> You still read/write JSON everywhere.<br><strong>Add a “prompt codec”:</strong> encode(json) → toonString.<br><strong>(Optional) decode:</strong> If you ever receive TOON (rare), decode(toon) → json.</p><pre>import { encode, decode } from &#39;@toon-format/toon&#39;;<br><br>const toon = encode({ users: [{ id: 1, name: &#39;Ada&#39;, role: &#39;admin&#39; }] });<br>const backToJson = decode(toon); // { users: [ ... ] }</pre><p>Good to keep in mind:<br>🔹 <strong>Validation:</strong> keep validating your <em>JSON</em> with JSON Schema as usual; TOON is just your <strong>transport to the model</strong>.<br>🔹 <strong>Observability:</strong> log prompt sizes (tokens) before/after; set SLOs for latency/cost.<br>🔹 <strong>Security &amp; PII:</strong> compactness doesn’t replace data-minimization; redact before encoding.<br>🔹 <strong>Governance:</strong> document when to use TOON vs JSON (simple rule: <em>LLM input only</em>).<br>🔹 <strong>Team onboarding:</strong> add a short README &amp; examples; include the CLI in dev containers.<br>🔹 <strong>Fallback:</strong> feature flag TOON so a single flip reverts to JSON if any issue surfaces.</p><blockquote>I wouldn’t “replace JSON” but keep JSON for code and contracts, <strong>convert to TOON at the last mile</strong> for LLM prompts where data is “rows of similar objects.” That gives you measurable <strong>cost/latency wins</strong> with almost no risk to the rest of your system. For <strong>deep, nested configs</strong>, stay with JSON. <br>In short: <strong>JSON for systems, TOON for prompts.</strong></blockquote><p>Reference:</p><p><a href="https://github.com/toon-format/toon/blob/main/README.md">https://github.com/toon-format/toon/blob/main/README.md</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b71353f1a4d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Error Boundaries in the Real World]]></title>
            <link>https://medium.com/@chandralekha-selvam/react-error-boundaries-in-the-real-world-6aac9d453273?source=rss-7f0675f5d3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6aac9d453273</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[error-handling]]></category>
            <dc:creator><![CDATA[Chandralekha S]]></dc:creator>
            <pubDate>Wed, 01 Oct 2025 18:00:25 GMT</pubDate>
            <atom:updated>2025-10-01T18:00:25.162Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZAzxuDKNOq5_L7AQPVdNOA.png" /></figure><p><strong>What is an Error Boundary?</strong></p><p>An <strong>Error Boundary</strong> is a React component that <strong>catches JavaScript errors</strong> that occur <strong>while rendering</strong> a subtree (or in its lifecycle), <strong>shows a safe fallback UI</strong>, and optionally <strong>logs</strong> the error. Think of it as a <strong>seatbelt</strong> around risky parts of your UI.</p><p><strong>Why React introduced them</strong></p><p>Before React 16, a render error in a child component could <strong>unmount the entire app</strong> (white screen). Error Boundaries (added in <strong>React 16</strong>) let you <strong>contain the blast radius</strong> — only the broken part shows a friendly message; the rest of the page stays alive.</p><p><strong>What problem do they solve?</strong></p><p>☑ <strong>Containment:</strong> If one widget crashes (e.g., a chart or third-party embed), the rest of the screen still works.<br>☑ <strong>Clarity for users:</strong> Show a simple, calm message + a <strong>Retry</strong> button.<br>☑ <strong>Developer visibility:</strong> Log error details (<strong>what failed, where, when</strong>) so you can fix it fast.</p><p><strong>When do boundaries run? (lifecycle &amp; timing)</strong></p><p>→ Inside a boundary, React calls two special methods when a <strong>child</strong> throws during render/lifecycle:</p><p>→ static getDerivedStateFromError(error) — <strong>synchronously</strong> sets state so the fallback UI can render <strong>in the same commit</strong>.<br>→ componentDidCatch(error, info) — runs <strong>after</strong> render to let you <strong>log</strong> details (error, componentStack).</p><pre>Child render throws <br>        ↓<br>Error bubbles to nearest boundary <br>        ↓<br>Boundary.setState({ hasError: true }) via getDerivedStateFromError<br>        ↓<br>React commits fallback UI for that subtree <br>        ↓<br>componentDidCatch logs details</pre><p>The boundary (class component today)</p><pre>class ErrorBoundary extends React.Component {<br>  state = { hasError: false };<br><br>  static getDerivedStateFromError() {<br>    return { hasError: true }; // show fallback this render<br>  }<br><br>  componentDidCatch(error, info) {<br>    // Send to your logger (Sentry/Datadog/console)<br>    console.log(&quot;Logged error:&quot;, {<br>      name: error?.name,<br>      message: error?.message,<br>      stack: error?.stack,<br>      componentStack: info?.componentStack,<br>      when: new Date().toISOString(),<br>    });<br>  }<br><br>  reset = () =&gt; this.setState({ hasError: false });<br><br>  render() {<br>    if (this.state.hasError) {<br>      // Accept a render prop so the fallback can get reset()<br>      return this.props.fallback?.({ onRetry: this.reset }) ?? null;<br>    }<br>    return this.props.children;<br>  }<br>}</pre><p>A friendly fallback UI (what users see)</p><pre>function WidgetError({ onRetry }) {<br>  return (<br>    &lt;div style={{ padding: 16, borderRadius: 12, border: &quot;1px solid #fecaca&quot;, background: &quot;#fff1f2&quot; }}&gt;<br>      &lt;h3 style={{ margin: 0 }}&gt;We hit a snag&lt;/h3&gt;<br>      &lt;p style={{ margin: &quot;8px 0 12px&quot; }}&gt;<br>        This section couldn’t load right now. The rest of the page is fine.<br>      &lt;/p&gt;<br>      &lt;button onClick={onRetry} style={{ padding: &quot;8px 12px&quot;, borderRadius: 8, border: 0, background: &quot;#111827&quot;, color: &quot;#fff&quot; }}&gt;<br>        Try again<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>A child that sometimes crashes (realistic bug)</p><pre>function SalesGraph({ simulateError }) {<br>  if (simulateError) {<br>    // Classic render-time error:<br>    throw new Error(&quot;items.map is not a function&quot;);<br>  }<br><br>  const items = [&quot;Q1: ↑&quot;, &quot;Q2: →&quot;, &quot;Q3: ↑↑&quot;, &quot;Q4: ↑&quot;];<br>  return (<br>    &lt;div&gt;<br>      &lt;h4 style={{ margin: 0 }}&gt;Sales Trend&lt;/h4&gt;<br>      &lt;ul style={{ margin: &quot;6px 0 0 16px&quot; }}&gt;<br>        {items.map((it) =&gt; &lt;li key={it}&gt;{it}&lt;/li&gt;)}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Parent page: contain the risky part + retry by re-mounting</h3><pre>function App() {<br>  const [simulateError, setSimulateError] = React.useState(false);<br>  const [key, setKey] = React.useState(0); // re-mount child to &quot;reset&quot; it<br><br>  return (<br>    &lt;main style={{ display: &quot;grid&quot;, gridTemplateColumns: &quot;1fr 1fr 1fr&quot;, gap: 16, fontFamily: &quot;Inter, system-ui, sans-serif&quot; }}&gt;<br>      &lt;section style={box}&gt;&lt;h3&gt;Announcements&lt;/h3&gt;&lt;p&gt;Q4 targets go live next week.&lt;/p&gt;&lt;/section&gt;<br><br>      &lt;section style={box}&gt;<br>        &lt;label style={{ display: &quot;flex&quot;, gap: 8, alignItems: &quot;center&quot;, marginBottom: 8 }}&gt;<br>          &lt;input type=&quot;checkbox&quot; checked={simulateError} onChange={e =&gt; setSimulateError(e.target.checked)} /&gt;<br>          Cause widget error (demo)<br>        &lt;/label&gt;<br><br>        &lt;ErrorBoundary fallback={({ onRetry }) =&gt; (<br>          &lt;WidgetError onRetry={() =&gt; { onRetry(); setKey(k =&gt; k + 1); }} /&gt;<br>        )}&gt;<br>          &lt;SalesGraph key={key} simulateError={simulateError} /&gt;<br>        &lt;/ErrorBoundary&gt;<br>      &lt;/section&gt;<br><br>      &lt;section style={box}&gt;&lt;h3&gt;Quick Links&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;Reports&lt;/li&gt;&lt;li&gt;Billing&lt;/li&gt;&lt;li&gt;Support&lt;/li&gt;&lt;/ul&gt;&lt;/section&gt;<br>    &lt;/main&gt;<br>  );<br>}<br><br>const box = { background: &quot;#fff&quot;, border: &quot;1px solid #e5e7eb&quot;, borderRadius: 12, padding: 16 };</pre><h3>What a user sees (real UI behavior)</h3><p>→ <strong>Normal state:</strong> The dashboard shows <em>Announcements</em>, <strong>Sales Trend</strong>, and <em>Quick Links</em>.<br>→ <strong>Crash state:</strong> Toggle “Cause widget error” → The <strong>Sales Trend</strong> panel turns into a <strong>soft red card</strong> with <em>“We hit a snag”</em> and a <strong>Try again</strong> button. <strong>Other panels stay interactive.<br></strong>→ <strong>Retry:</strong> Clicking <strong>Try again</strong> resets the boundary and <strong>re-mounts</strong> the widget (via the key), so transient problems can self-heal.</p><p>Parent ↔ Child impact (how containment works)</p><p>→ The <strong>boundary lives above</strong> the risky child in the tree.<br>→ If the <strong>child throws during render</strong>, the error <strong>bubbles up</strong> to the nearest boundary.<br>→ React <strong>commits the fallback</strong> only for that subtree; <strong>siblings and parent remain</strong>.<br>→ You can scope multiple boundaries to isolate different sections (e.g., each dashboard card).</p><p><strong>Anti-pattern:</strong> one giant boundary wrapping the entire app. You’ll avoid the white screen, but you lose the <strong>granularity</strong> that keeps most of the page usable.</p><p>Errors that are <strong>caught</strong> vs <strong>not caught</strong></p><p><strong>✅ Caught by boundaries</strong></p><p>↳ Rendering errors</p><p>e.g., items.map is not a function<br>e.g., Cannot read properties of undefined (reading &#39;length&#39;)</p><p>↳ Errors in child lifecycle (class lifecycles; in function components, code that runs during render phase)</p><p><strong>❌ Not caught by boundaries</strong></p><p>↳ <strong>Event handlers</strong> (wrap with try/catch yourself):</p><pre>&lt;button onClick={() =&gt; { try { riskyClick() } catch (e) { setError(e) } }}&gt;<br>  Save<br>&lt;/button&gt;</pre><p>↳ <strong>Async work</strong> outside render:</p><pre>useEffect(() =&gt; {<br>  (async () =&gt; {<br>    try { await fetchData() }<br>    catch (e) { setError(e) } // show your own fallback for data loading<br>  })();<br>}, []);</pre><p>↳ <strong>Server-side rendering</strong> (boundaries kick in on the client after hydration)</p><h3>UX tips</h3><p>🔹 <strong>Plain language:</strong> “We hit a snag. This section couldn’t load.”<br>🔹 <strong>Reassure:</strong> “The rest of the page is fine.”<br>🔹 <strong>Action:</strong> “Try again” (re-mount the child), “Refresh”, “Contact support”.<br>🔹 <strong>Don’t blame the user:</strong> No scary stack traces in the UI.<br>🔹 <strong>Log quietly:</strong> Send error details to monitoring tools; don’t expose internals.</p><h3>Production checklist</h3><p>→ Place boundaries around <strong>risk zones</strong> (charts, WYSIWYG editors, 3rd-party SDKs)<br>→ Provide a <strong>friendly fallback</strong> with <strong>Retry<br></strong>→ <strong>Log</strong> error, componentStack, when, and a <strong>correlation ID</strong> if you have one<br>→ <strong>Avoid giant app-wide boundary</strong>; prefer <strong>scoped</strong> ones<br>→ Add a <strong>feature flag</strong> to toggle enhanced logging for a session<br>→ <strong>Test</strong> a forced crash to verify fallback + logging</p><p><strong>Tiny test (Jest + React Testing Library):</strong></p><pre>// Pseudocode<br>it(&quot;shows fallback when child throws&quot;, () =&gt; {<br>  render(<br>    &lt;ErrorBoundary fallback={() =&gt; &lt;div&gt;fallback&lt;/div&gt;}&gt;<br>      &lt;CrashingChild /&gt; {/* throws during render */}<br>    &lt;/ErrorBoundary&gt;<br>  );<br>  expect(screen.getByText(/fallback/i)).toBeInTheDocument();<br>});</pre><p>What they don’t solve (limitations)</p><p>→ <strong>Not for event handlers.</strong> Errors in onClick or onChange aren’t caught. Use try/catch in the handler.<br>→ <strong>Not for async outside render.</strong> Errors in fetch, Promise callbacks, or setTimeout aren’t caught unless they surface during render. Handle with .catch or try/await/catch and set error state yourself.<br>→ <strong>Not for server-side rendering.</strong> There’s no DOM; boundaries work on the client after hydration.<br>→ <strong>Not a replacement for validation or guard logic.</strong> They’re a last-resort safety net.</p><p>Final Thoughts:</p><p>🔹 Error Boundaries are <strong>safety nets</strong> for React render errors.<br>🔹 They <strong>contain</strong> crashes to a small area, <strong>log</strong> what broke, and let users <strong>retry</strong>.<br>🔹 They <strong>don’t</strong> catch event-handler or async errors — handle those where they occur.<br>🔹 Use <strong>scoped boundaries</strong> around risky widgets for the best UX.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6aac9d453273" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arrays vs Objects: A Practical Guide to Destructuring]]></title>
            <link>https://medium.com/@chandralekha-selvam/arrays-vs-objects-a-practical-guide-to-destructuring-3bf4ae49c776?source=rss-7f0675f5d3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bf4ae49c776</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[destructuring]]></category>
            <dc:creator><![CDATA[Chandralekha S]]></dc:creator>
            <pubDate>Wed, 24 Sep 2025 17:17:37 GMT</pubDate>
            <atom:updated>2025-09-24T17:17:37.677Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWstQhZjkvMJw-hPVKfmWQ.jpeg" /></figure><h3>ES6 Destructuring, Demystified</h3><p><strong>Arrays vs. Objects — common uses, simple examples, tips, and gotchas</strong></p><blockquote><em>Destructuring is the tiny bit of ES6 syntax that removes a </em>lot<em> of boilerplate.<br> Basic: </em><strong><em>Arrays are position-based. Objects are name-based.</em></strong></blockquote><h3>0) The Basic</h3><p><strong>Array destructuring</strong>: the left side mirrors the <strong>positions</strong> in a list.</p><pre>const [first, second] = [10, 20]; // first=10, second=20</pre><p><strong>Object destructuring</strong>: the left side mirrors the <strong>keys</strong> in an object.</p><pre>const { x, y } = { x: 1, y: 2 }; // x=1, y=2</pre><blockquote><strong><em>Defaults only apply to </em></strong><strong><em>undefined, not </em></strong><strong><em>null.</em></strong><em><br></em><strong><em>Rest</em></strong><em> collects “the rest” (leftovers).</em></blockquote><h3>Where dev’s make mistake(and how to fix it)</h3><h3>1) “Why didn’t my default run?”</h3><p><strong>Spot it</strong></p><pre>const [count = 1] = [null]; // expecting 1, got null</pre><p><strong>Why</strong><br> Defaults only apply to <strong>undefined</strong>, not null.</p><p><strong>Fix</strong></p><pre>const [count = 1] = [undefined]; // → 1<br>// or normalize upstream: value ?? 1 (nullish coalescing)</pre><h3>2) “Cannot read properties of undefined” on nested objects</h3><p><strong>Spot it</strong></p><pre>const user = {};<br>const { profile: { email } } = user; // profile is undefined</pre><p><strong>Why</strong><br> You tried to drill into a missing object.</p><p><strong>Fix (safe default for the parent)</strong></p><pre>const { profile: { email } = {} } = user; // email = undefined (no crash)</pre><h3>3) Assigning to existing vars without parentheses</h3><p><strong>Spot it</strong></p><pre>let title, year;<br>// SyntaxError:<br>{ title, year } = { title: &quot;ES6&quot;, year: 2015 };</pre><p><strong>Why</strong><br> JS reads {} as a block, not a pattern.</p><p><strong>Fix</strong></p><pre>({ title, year } = { title: &quot;ES6&quot;, year: 2015 });</pre><h3>4) Mixing up array vs object patterns</h3><p><strong>Spot it</strong></p><pre>const arr = [10, 20];<br>// const { a, b } = arr;   // not how arrays work</pre><p><strong>Why</strong><br> Arrays use <strong>positions</strong>, not keys.</p><p><strong>Fix</strong></p><pre>const [a, b] = arr; // a=10, b=20</pre><h3>5) Rest (...rest) not placed last</h3><p><strong>Spot it</strong></p><pre>const [head, ...rest, tail] = [1,2,3]; // SyntaxError</pre><p><strong>Why</strong><br> Rest must be the <strong>final</strong> item.</p><p><strong>Fix</strong></p><pre>const [head, ...rest] = [1,2,3]; // rest=[2,3]</pre><h3>6) Shadowing / duplicate names</h3><p><strong>Spot it</strong></p><pre>const { id } = a;<br>const { id } = b; // Duplicate declaration in the same scope</pre><p><strong>Why</strong><br> Destructuring <strong>declares</strong> variables.</p><p><strong>Fix (rename)</strong></p><pre>const { id: aId } = a;<br>const { id: bId } = b;</pre><h3>7) Destructuring function params that might be missing</h3><p><strong>Spot it</strong></p><pre>function renderUser({ name }) { /* ... */ }<br>renderUser(); // Cannot destructure &#39;name&#39; of undefined</pre><p><strong>Why</strong><br> You’re destructuring undefined.</p><p><strong>Fix (default the whole param)</strong></p><pre>function renderUser({ name = &quot;Guest&quot; } = {}) { /* ... */ }</pre><h3>8) Defaults that do heavy work — even when you don’t need them</h3><p><strong>Spot it</strong></p><pre>function heavy() { console.log(&quot;ran&quot;); return 42; }<br>const [v = heavy()] = [5]; // EXPECTED: avoid heavy(), but did it run?</pre><p><strong>Why</strong><br> Good news: defaults are <strong>lazy</strong> — they run only if the value is undefined.<br> But it’s easy to forget and worry. Verify like this:</p><p><strong>Fix (proof)</strong></p><pre>const [x = heavy()] = [5]; // (no log) heavy() NOT called<br>const [y = heavy()] = [undefined]; // logs &quot;ran&quot;</pre><h3>9) Accidentally destructuring from a non-iterable / wrong shape</h3><p><strong>Spot it</strong></p><pre>const notArray = null;<br>const [a] = notArray; // TypeError: not iterable</pre><p><strong>Why</strong><br> Array patterns need an <strong>iterable</strong>. Null/undefined isn’t one.</p><p><strong>Fix</strong></p><pre>const list = notArray ?? []; // default to empty array<br>const [a] = list; // a = undefined (safe)</pre><h3>10) Using rest on objects expecting deep clone</h3><p><strong>Spot it</strong></p><pre>const obj = { nested: { x: 1 }, a: 2 };<br>const { a, ...copy } = obj;<br>copy.nested.x = 99; // Also changes obj.nested.x</pre><p><strong>Why</strong><br> Object rest is a <strong>shallow</strong> copy.</p><p><strong>Fix</strong></p><pre>const deep = JSON.parse(JSON.stringify(obj)); // simple (but lossy) deep clone<br>// or use a real deep-clone util for complex data</pre><h3>11) Confusion with computed property names</h3><p><strong>Spot it</strong></p><pre>const key = &quot;score&quot;;<br>const { key: value } = { score: 10 }; // value = undefined</pre><p><strong>Why</strong><br> key is taken literally; you wanted the <strong>value of</strong> key.</p><p><strong>Fix</strong></p><pre>const { [key]: value } = { score: 10 }; // value = 10</pre><h3>12) Array holes behave like undefined</h3><p><strong>Spot it</strong></p><pre>const arr = [, 2]; // hole at index 0<br>const [a = 1, b] = arr; // a=1 (default kicks in), b=2</pre><p><strong>Why</strong><br> A “hole” is treated as undefined, so defaults apply.</p><p><strong>Fix</strong><br> No fix needed — just know it and use defaults intentionally.</p><h3>13) Nested destructuring without guard defaults</h3><p><strong>Spot it</strong></p><pre>const name = {};<br>const { theme: { color } } = name; // theme is undefined</pre><p><strong>Why</strong><br> Same as #2, deeper in the tree.</p><p><strong>Fix (guard the parent)</strong></p><pre>const { theme: { color = &quot;black&quot; } = { color: &quot;black&quot; } } = name;</pre><h3>14) Returning an object but trying to array-destructure (or vice versa)</h3><p><strong>Spot it</strong></p><pre>function getUser() { return { id: 1, name: &quot;Kalam&quot; }; }<br>// const [id, name] = getUser(); // TypeError: not iterable</pre><p><strong>Why</strong><br> Shapes don’t match.</p><p><strong>Fix</strong></p><pre>const { id, name } = getUser(); // object ↔ object</pre><h3>15) Over-destructuring in loops (micro perf + readability)</h3><p><strong>Spot it</strong></p><pre>for (const {id, name, email} of users) {<br>  // only used id<br>}</pre><p><strong>Why</strong><br> You’re extracting more than you need.</p><p><strong>Fix</strong></p><pre>for (const {id} of users) {<br>  // clear &amp; minimal<br>}</pre><h3>16) Forgetting that object destructuring sees inherited props</h3><p><strong>Spot it</strong></p><pre>const proto = { a: 1 };<br>const child = Object.create(proto);<br>child.b = 2;<br>const { a, b } = child; // a=1 (from prototype), b=2</pre><p><strong>Why</strong><br> It uses normal property lookup (includes prototype chain).</p><p><strong>Fix (own props only)</strong></p><pre>const { a, b } = Object.assign({}, child); // or use Object.hasOwn in checks</pre><h3>Quick “fix-it” checklist</h3><p>→ Default whole params: function f({x=1} = {}) {}<br>→ Guard nested: { parent: { child } = {} }<br>→ Arrays need iterables; objects need keys that exist (or defaults)<br>→ Rest must be last; remember it’s shallow<br>→ Use ({ a } = obj) for assignment; { a } = obj for declaration<br>→ Rename to avoid duplicate declarations: { id: userId }<br>→ Use ?? to normalize null/undefined when you want the default to kick in</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bf4ae49c776" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Stop Sprinkling Memo Everywhere”: A Practical Guide to useMemo vs useCallback]]></title>
            <link>https://medium.com/@chandralekha-selvam/stop-sprinkling-memo-everywhere-a-practical-guide-to-usememo-vs-usecallback-5e042299788e?source=rss-7f0675f5d3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e042299788e</guid>
            <category><![CDATA[ui-performance]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Chandralekha S]]></dc:creator>
            <pubDate>Tue, 02 Sep 2025 16:58:34 GMT</pubDate>
            <atom:updated>2025-09-02T16:58:34.769Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>useMemo caches a <em>value</em></strong>, <strong>useCallback caches a <em>function</em></strong>. Both help you <strong>skip work</strong>—but only when that work is actually expensive or prevents re-renders you care about.</p><h4>Why these hooks exist (and what they do)</h4><ul><li><strong>useMemo(fn, deps)</strong> → returns the <strong>cached result</strong> of fn until any dependency changes. Great for <strong>expensive calculations</strong> or for <strong>stabilizing objects/arrays</strong> you pass to children or effects.</li><li><strong>useCallback(fn, deps)</strong> → returns the <strong>same function reference</strong> between renders until any dependency changes. Useful when passing handlers to <strong>memoized children</strong> or as <strong>stable dependencies</strong> for effects.</li></ul><p>FYI: useCallback(fn, deps) is effectively useMemo(() =&gt; fn, deps). <a href="https://react.dev/reference/react/useMemo">React’s docs</a> position both as <strong>caching tools</strong> to avoid unnecessary work.</p><h4>How it actually works</h4><p>React keeps an internal cache per component. On each render it:</p><ol><li>Checks the deps array.</li><li>If unchanged → <strong>returns the cached value/function</strong>.</li><li>If changed → <strong>recomputes</strong> (for useMemo) or <strong>rebuilds</strong> the function (for useCallback) and updates the cache.</li></ol><p>These hooks <strong>don’t</strong> magically speed up everything; they trade <strong>a little memory + bookkeeping</strong> to <strong>skip bigger work later</strong>. <br>With React 19’s <strong>React Compiler</strong>, some of this memoization can be automated — meaning you may need fewer manual memos over time.</p><h4>When to use which (and when not to)</h4><p>Use useMemo when…<br>🔹 You perform <strong>heavy derived calculations</strong> (sort, group, aggregate, expensive filters).<br>🔹 You construct <strong>stable objects/arrays</strong> used as props or effect deps (to avoid re-runs).<br>Use useCallback when…<br>🔹 You pass a handler to a <strong>React.memo child</strong> (or a list of them) and want to <strong>avoid re-renders</strong> from changing function identities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8JOEE6lA1aAn07AfIt9_rg.gif" /><figcaption>useCallback VS useMemo</figcaption></figure><p>🚫 Don’t use either when…</p><p>The work is <strong>minimal</strong> (map a 20-item array) or the child <strong>isn’t memoized</strong> — you’ll add overhead for no win.</p><p>You’re only trying to “feel” optimized. <strong>Profile first.</strong> (React docs: use them to <strong>skip work</strong>, not by default.)</p><h4>Real-world use case: Large data grid (filters, sorting, row actions)</h4><p><strong>Scenario:</strong> A telecom analytics dashboard rendering <strong>50k CDR rows</strong>. You have filter pills, a sort dropdown, and per-row action buttons rendered by a memoized Row component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mRPg4Z69XGZkezKWTMreTw.gif" /></figure><p>Parent (DataGrid) — compute once, not every render</p><pre>function DataGrid({ rows, filters, sortBy }) {<br>  // 1) Heavy derive: filter + sort the big dataset<br>  const visible = useMemo(() =&gt; {<br>    let out = rows;<br>    if (filters.length) out = out.filter(r =&gt; filters.every(f =&gt; f(r)));<br>    if (sortBy) out = [...out].sort(sortBy.compare); // clone before sort<br>    return out;<br>  }, [rows, filters, sortBy]);<br><br>  // 2) Stable handlers for memoized children<br>  const handleSelect = useCallback((rowId: string) =&gt; {<br>    // … selection logic …<br>  }, []); // no row-level deps here<br><br>  return (<br>    &lt;VirtualList<br>      items={visible}<br>      itemRenderer={(row) =&gt; (<br>        &lt;Row key={row.id} row={row} onSelect={handleSelect} /&gt;<br>      )}<br>    /&gt;<br>  );<br>}</pre><p>Child (Row) — skip re-render if props didn’t change</p><pre>const Row = React.memo(function Row({ row, onSelect }) {<br>  return (<br>    &lt;div className=&quot;row&quot;&gt;<br>      &lt;span&gt;{row.msisdn}&lt;/span&gt;<br>      &lt;button onClick={() =&gt; onSelect(row.id)}&gt;Select&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>});</pre><p><strong>Why this works</strong></p><p>☑ visible only recomputes when inputs change (<strong>useMemo</strong>).</p><p>☑ onSelect keeps the same reference across renders (<strong>useCallback</strong>), so Row components don’t re-render pointlessly (they’re wrapped in <strong>React.memo</strong>)</p><p>“Do” vs “Don’t” patterns</p><p>✅ Do: Memoize expensive derived data</p><pre>const expensive = useMemo(() =&gt; derive(bigList), [bigList]);</pre><p>❌ Don’t: Memoize trivial values or every tiny map</p><pre>// Overkill: adds overhead, no meaningful skip<br>const doubled = useMemo(() =&gt; arr.map(x =&gt; x * 2), [arr]);</pre><p>✅ Do: Stabilize callbacks passed to memoized children</p><pre>const onSave = useCallback((id) =&gt; save(id), [save]);</pre><p>❌ Don’t: Wrap every function by default</p><pre>// Pointless if child isn&#39;t memoized or the handler is cheap<br>const onBlur = useCallback(() =&gt; setTouched(true), []);</pre><p>✅ Do: Use memo to stabilize objects in effect deps</p><pre>const query = useMemo(() =&gt; ({ limit, sort }), [limit, sort]);<br>useEffect(() =&gt; fetchData(query), [query]);</pre><p>❌ Don’t: Recreate objects inline and wonder why effect keeps firing</p><pre>useEffect(() =&gt; fetchData({ limit, sort }), [limit, sort]); // new object each time</pre><h4>Watch out: stale closures</h4><p>If your callback captures changing state but has an empty deps array, it will <strong>see stale values</strong>. Keep deps complete, or restructure.</p><p>Why identity matters</p><p><strong>React.memo</strong> skips re-render if <strong>props are equal</strong> (shallow compare with Object.is by default). If your handler prop is a <strong>new function each render</strong>, the child will re-render even if logic is unchanged. <strong>useCallback preserves identity</strong> to work with React.memo</p><p><strong>useMemo</strong> helps when equality is by reference (objects/arrays). Without it, brand-new {} or [] props <strong>break equality</strong> and cause re-renders or effect re-runs.</p><p>How these fit</p><pre>[State/Props change]<br>        │<br>        ▼<br>   Re-render parent<br>        │<br>        ├─ useMemo(...)  ──► returns cached DERIVED DATA  (skip heavy work)<br>        │<br>        ├─ useCallback(...) ─► returns stable HANDLER     (preserve identity)<br>        │<br>        ▼<br>  Pass props to children ──► children wrapped in React.memo decide to re-render</pre><ul><li>If <strong>derived data</strong> didn’t change → children likely <strong>stay put</strong>.</li><li>If <strong>handler identity</strong> didn’t change → memoized children <strong>don’t blink</strong></li></ul><h4>Troubleshooting quick tips:</h4><p>🔹 <strong>“My memo still recomputes!”</strong> → A dep is changing by reference (new array/object). Stabilize it (memo or ref) or compute upstream.<br>🔹 <strong>“My memoized callback keeps changing!”</strong> → Check the deps list; something inside the closure varies each render.<br>🔹 <strong>“Effect fires too often.”</strong> → Don’t pass inline objects/functions as deps; memoize them or restructure.<br>🔹 <strong>“Do I need these at all?”</strong> → With React Compiler, many cases are automated; <strong>measure first</strong> before adding manual memos.</p><h4>Add useMemo if…</h4><p>🔹 The computation is <strong>noticeably expensive<br></strong>🔹 You’re creating <strong>objects/arrays</strong> used as props or deps<br>🔹 You’ve <strong>measured</strong> a benefit (Profiler / flamegraph)</p><h4>Add useCallback if…</h4><p>🔹 The child is <strong>React.memo</strong> (or otherwise memoized)<br>🔹 The handler identity triggers <strong>re-renders</strong> you want to avoid<br>🔹 The function is an <strong>effect dependency</strong> and should be stable</p><p>References:</p><ul><li><a href="https://react.dev/reference/react/useCallback">useCallback - React</a></li><li><a href="https://react.dev/reference/react/useMemo">useMemo - React</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e042299788e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Global Icon —  Born from Grit, Heart, and Harmony]]></title>
            <link>https://medium.com/@chandralekha-selvam/a-global-icon-born-from-grit-heart-and-harmony-6e54eb613cb9?source=rss-7f0675f5d3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e54eb613cb9</guid>
            <category><![CDATA[discipline]]></category>
            <category><![CDATA[teamwork]]></category>
            <category><![CDATA[mindset]]></category>
            <category><![CDATA[life-lessons]]></category>
            <category><![CDATA[bts-army]]></category>
            <dc:creator><![CDATA[Chandralekha S]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 18:58:49 GMT</pubDate>
            <atom:updated>2025-07-03T18:58:49.489Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Global Icon — Born from Grit, Heart, and Harmony</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*guR9XCnuTPH267-0KdETiA.jpeg" /><figcaption><a href="https://en.wikipedia.org/wiki/BTS">BTS</a> Group Pic taken at the Whitehouse May 2022</figcaption></figure><blockquote><strong>How a boy band became the voice of a generation</strong></blockquote><p>For many, music is a safe haven — a place to hide, to heal.</p><p>My husband, for instance, has a playlist for every mood.<br>He invests in high-quality earphones just to feel the bass right.<br>He’s often humming something — in the kitchen, in the car, sometimes even while working. Music is his constant companion … right after me, of course.</p><p>But for me, that place was always found in books.</p><p>I have to admit — I’ve never really been someone who listens to music deeply. I’d enjoy the tune, for sure, but I could barely remember the lyrics beyond the first line. It’s not something I never expected to feel connected to!!</p><p>But that changed the day a close friend, who had moved to Korea for her Master’s, sent me a songs from the album <em>“The Most Beautiful Moment in Life”</em> — and though I couldn’t understand the language my friend Archana used to translate it to me in Tamil.. something in it just… stayed.</p><p>Not the beat, not the melody — but the <strong>feeling</strong>.</p><p>It was quiet, emotional, and reflective — like a conversation I didn’t know I needed.</p><p>Through her, I started following BTS casually — catching glimpses of their journey, watching a few interviews, and reading about their early training days.</p><p>What struck me most wasn’t just their talent, but their <strong>fearless persistence</strong> — how they embraced every criticism, how they’d approach strangers on the street just to get someone to listen to their music.</p><h4>They weren’t chasing fame — they were <strong>fighting to be heard</strong>.</h4><blockquote><em>And then came the</em><strong><em> Love Yourself era</em></strong><em>.</em></blockquote><p>That album didn’t just sound good. It <em>felt right</em>.</p><p>It mirrored the exact phase I was navigating — learning to unlearn self-criticism, practicing care, and realising that loving yourself isn’t self-indulgence… it’s survival.</p><p>Then RM stood on the UN stage and said:</p><blockquote><strong><em>“Speak yourself.”</em></strong></blockquote><blockquote><strong><em>That wasn’t just a speech — it felt like permission.</em></strong></blockquote><blockquote><strong><em>To show up as I am. Flawed, afraid, still figuring things out — and still worthy of a voice.</em></strong></blockquote><p>“They just kept showing up — doing the same exhausting, repetitive thing day after day. The kind of grind most of us would quit halfway through. Even when the results weren’t instant, even when the world wasn’t clapping yet, they stayed consistent. And somewhere along the way — without even realising it — success started walking beside them.”</p><p>Quietly at first, then louder than anyone expected.</p><p>I went from <em>watching</em> BTS… <strong>to <em>walking with them</em></strong>. 💜</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e54eb613cb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Thought Leadership means in an Agentic AI Era??]]></title>
            <link>https://medium.com/@chandralekha-selvam/what-thought-leadership-means-in-an-agentic-ai-era-fa5fcb70acfb?source=rss-7f0675f5d3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa5fcb70acfb</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[human-vs-machine]]></category>
            <category><![CDATA[future-of-work]]></category>
            <category><![CDATA[emotional-intelligence]]></category>
            <category><![CDATA[thought-leadership]]></category>
            <dc:creator><![CDATA[Chandralekha S]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 18:36:22 GMT</pubDate>
            <atom:updated>2025-06-30T18:36:22.319Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In a world where machines can simulate intentions, being truly human becomes the rarest form of Leadership!!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xsOe_2YJ0soCBOM6mBHWRA.jpeg" /><figcaption>Simulated Thought vs. Conscious Mind: Who Leads the Future?</figcaption></figure><p>The Curve no longer waits for us!</p><p>The Thought Leadership once meant being ahead of the curve. But in 2025, the curve moves faster than cognition and sometimes, beyond the human participation.</p><p>Agentic AI systems like AutoGPT, CrewAI, LangGraph and BabyAGI are now capable of complex reasoning, task planning and autonomous execution. These agents act with a very apparent purpose — prompting themselves, delegating to other agents and navigating towards goals. It’s a transformation of capability.</p><p>And a disruption of meaning!</p><p>To represent this evolution, I used the Gaussian (normal distribution) function not to reflect hard data but something less measurable, but to capture the growing tension, <strong>shifting influence of human cognition vs. Agentic AI across increasing levels of complexity</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*bxkHbsNxLSmflFUe2oODMQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EFaRcFizesCJxE3WkgBvkg.png" /></figure><p>Though the above is just a conceptual and not a hard data, It shows how humans have long thrived across a wide range of tasks — offering flexibility, creativity, and emotional depth, while agentic AI is now beginning to <strong>concentrate its influence</strong> — and perhaps surpass — in domains requiring speed, scale, and recursive reasoning.</p><p>The point isn’t to claim one is superior.</p><blockquote><em>As AI accelerates its cognitive simulations, </em><strong><em>we must double down on what makes our thinking truly human</em></strong><em> — judgment, emotion, ethics, and the courage to pause when machines only proceed.</em></blockquote><p>AI can simulate Thought but not Leadership.</p><p>Traditionally Thought Leadership meant originality, experience and intuition. It is deeply rooted in our human perception — insights gained over time, articulated with authenticity.</p><p>Agentic AI systems, however, are now capable of:</p><ol><li>Generating strategic foresight</li><li>Producing creative content</li><li>Automating decision-making flows</li></ol><p>These were once uniquely human traits yet this is where the stress is: <em>AI Lacks lived experiences. It doesn’t feel fear or uncertainty. It doesn’t face real-world accountability.</em></p><p>So What does that mean for the human Thought Leadership ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gP7g0piT5lh--vyocZ0IzA.png" /><figcaption>Human vs Agentic AI Thought Simulation</figcaption></figure><p>Why Thought Leadership is still important — more than ever</p><ol><li>Information is abundant. Judgement is Scarce.<br>Agentic AI can <em>simulate</em> thought. But it cannot Judge.<br>It cannot tell when data is enough Or when a narrative needs emotional context Or when a decision calls for a pause, not speed.<br>That’s where Thought Leadership thrives now — in applying discernment, not just producing output.</li><li>AI is a Mirror, Not a Mind.<br>Autonomous Agents reflect what we feed them: our data, our prompts, our biases. But they do not know who they are. They lack <strong><em>selfhood. </em></strong>They don’t grapple with contradictions or carry the weight of choice.<br><strong>A human leader does. And Must.</strong></li><li>Velocity ≠ Vision<br>In an AI-saturated world, speed is table stakes. But vision requires slowness. It calls for clarity amid chaos and for conviction when ambiguity reigns.<br><strong>AI can go fast. Humans must go deeper.</strong></li><li>Originality can’t be synthesised <br>AI recombines; it does not originate from emotion. The heartbreak behind a movement. The curiosity behind a question. The tension behind a story. These come from being human, not being trained.<br>Thought Leadership must now carry the emotional DNA AI lacks.</li></ol><p>So what does <strong>Thought Leadership</strong> actually means in this Agentic Era,</p><blockquote><strong>Saying something real</strong>, even if AI could say it faster<br><strong>Standing for something</strong>, not just sharing what trends<br><strong>Asking better questions</strong>, not giving prettier answers<br><strong>Curating meaning</strong>, not just generating content<br><strong>Owning imperfections</strong>, not just optimising for virality.</blockquote><p>In the age of agentic AI, true thought leadership is no longer about being louder, faster, or smarter.</p><p>It’s about being <strong>deeply human</strong>, and being brave enough to stay that way.</p><p>As machines get better at thinking, are we becoming too comfortable not thinking at all? The future isn’t just about what AI can do — it’s about what we choose not to lose.</p><p>Reference:</p><p><a href="https://mathworld.wolfram.com/NormalDistribution.html">Normal Distribution -- from Wolfram MathWorld</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa5fcb70acfb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mistakes to avoid when using useEffect — React Hooks]]></title>
            <link>https://medium.com/@chandralekha-selvam/mistakes-to-avoid-when-using-useeffect-react-hooks-2dce16ca68ea?source=rss-7f0675f5d3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2dce16ca68ea</guid>
            <category><![CDATA[react-tips]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Chandralekha S]]></dc:creator>
            <pubDate>Mon, 27 Mar 2023 18:39:11 GMT</pubDate>
            <atom:updated>2023-03-27T18:39:11.355Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mistakes to avoid when using useEffect — React Hooks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MsfwiiMgNRdnUgF--n7lAw.jpeg" /></figure><p>So every React developer would have used this <strong>useEffect</strong> everyday because it a very powerful feature in React. It used to perform the side effects in the functional components.</p><p>Here I have listed few of the common mistakes which will impact the application’s performance or could lead to any unexpected behavior.</p><ol><li><strong>Not including dependencies in the dependency array</strong></li></ol><p>The <strong>useEffect</strong> hook takes a second argument which is an array of dependencies. This array specifies the values that the effect depends on. If any of the dependencies change, the effect will be re-run. One common mistake is to not include all of the necessary dependencies in the array. This can lead to bugs and unexpected behavior.</p><pre>function MyComponent(props) {<br>  const [count, setCount] = useState(0);<br><br>  useEffect(() =&gt; {<br>    console.log(&#39;Count changed&#39;);<br>  }, []); // missing dependency array<br><br>  return (<br>    &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>      Click me ({count})<br>    &lt;/button&gt;<br>  );<br>}</pre><p>In the above example the effect is not dependent on any values, so an empty dependency array is used. However, the effect needs to run whenever the count state changes, so it should be added as a dependency.</p><p>2. <strong>Forgetting to cleanup effects</strong></p><p>When you use <strong>useEffect</strong> to register event listeners, timers or other external resources, it&#39;s important to clean them up when the component is unmounted. Otherwise, you might end up with memory leaks or other issues. One way to clean up effects is to return a cleanup function from the effect callback.</p><pre>function MyComponent(props) {<br>  useEffect(() =&gt; {<br>    const intervalId = setInterval(() =&gt; {<br>      console.log(&#39;Tick&#39;);<br>    }, 1000);<br><br>    return () =&gt; {<br>      clearInterval(intervalId);<br>    };<br>  }, []);<br><br>  return &lt;&gt;...&lt;/&gt;;<br>}</pre><p>here the effect sets up an interval timer and returns a cleanup function that clears the timer when the component unmounts.</p><p>3. <strong>Accidentally triggering infinite loops</strong></p><p>If you’re not careful, it’s easy to accidentally create infinite loops with <strong>useEffect</strong>. This can happen when the effect updates a value that causes the effect to run again, which updates the value again, and so on. To prevent this, you need to make sure that the effect only updates the necessary values.</p><pre>function MyComponent(props) {<br>  const [count, setCount] = useState(0);<br><br>  useEffect(() =&gt; {<br>    if (count &lt; 10) {<br>      setCount(count + 1);<br>    }<br>  }, [count]); // only run effect when count changes<br><br>  return &lt;div&gt;{count}&lt;/div&gt;;<br>}</pre><p>In this case the effect only updates the count state if it&#39;s less than 10. This prevents an infinite loop from occurring.</p><p>4. <strong>Not using the previous state or props values</strong></p><p>Sometimes, you need to access the previous state or props values in the effect. This can be done by using the function form of the state setter or by using a ref.</p><pre>function MyComponent(props) {<br>  const [count, setCount] = useState(0);<br>  const prevCountRef = useRef();<br><br>  useEffect(() =&gt; {<br>    prevCountRef.current = count;<br>  });<br><br>  const prevCount = prevCountRef.current;<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Current count: {count}&lt;/p&gt;<br>      &lt;p&gt;Previous count: {prevCount}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Click Here&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>so here the effect updates a ref to store the previous count value. The ref is then accessed outside of the effect to display the current and previous count values.</p><p>5. <strong>Running unnecessary effects</strong></p><p>Sometimes, you might have multiple effects in a component that depend on the same value. In this case, it’s important to make sure that only the necessary effects are run. You can do this by either combining the effects into a single effect or by using separate effects with different dependencies.</p><pre>function MyComponent(props) {<br>  const [count, setCount] = useState(0);<br>  const [text, setText] = useState(&#39;&#39;);<br><br>  useEffect(() =&gt; {<br>    console.log(&#39;Count changed&#39;);<br>  }, [count]); // only run effect when count changes<br><br>  useEffect(() =&gt; {<br>    console.log(&#39;Text changed&#39;);<br>  }, [text]); // only run effect when text changes<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;input value={text} onChange={e =&gt; setText(e.target.value)} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>there are two effects that depend on either the count or text state. By specifying different dependencies for each effect, only the necessary effect will run when the corresponding state value changes.</p><p>6. <strong>Forgetting to handle async effects properly</strong></p><p>If your effect involves asynchronous operations, it’s important to handle them properly to avoid bugs and race conditions. One common mistake is to forget to handle errors or to improperly use closures that reference stale state values.</p><pre>function MyComponent(props) {<br>  const [data, setData] = useState(null);<br><br>  useEffect(() =&gt; {<br>    fetchData()<br>      .then(result =&gt; setData(result))<br>      .catch(error =&gt; console.error(error));<br>  }, []); // run once on mount<br><br>  return &lt;div&gt;{data ? data.name : &#39;Loading...&#39;}&lt;/div&gt;;<br>}</pre><p>here in the above example the effect fetches data from an API and sets the result in state. However, if the API call fails, there’s no error handling, which could lead to unexpected behavior. Additionally, if the fetchData function uses a stale state value, it could also lead to bugs. To avoid these issues, you should handle errors properly and use the setData function to ensure that the state value is up-to-date. check the below code for error handling.</p><pre>function MyComponent(props) {<br>  const [data, setData] = useState(null);<br><br>  useEffect(() =&gt; {<br>    let isMounted = true;<br><br>    fetchData()<br>      .then(result =&gt; {<br>        if (isMounted) {<br>          setData(result);<br>        }<br>      })<br>      .catch(error =&gt; {<br>        console.error(error);<br>      });<br><br>    return () =&gt; {<br>      isMounted = false;<br>    };<br>  }, []); // run once on mount<br><br>  return &lt;div&gt;{data ? data.name : &#39;Loading...&#39;}&lt;/div&gt;;<br>}</pre><p>the effect uses a flag variable to keep track of whether the component is still mounted. This prevents the <strong>setData</strong> function from being called on a stale state value. Additionally, the effect returns a cleanup function to update the flag variable when the component unmounts, preventing any further state update.</p><p>By avoiding the above mentioned mistakes and following the best practises we can write effective and efficient React code.</p><p>Happy Coding !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2dce16ca68ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving Asynchronous JavaScript with Async/Await]]></title>
            <link>https://medium.com/@chandralekha-selvam/improving-asynchronous-javascript-with-async-await-e17d3cc5e1de?source=rss-7f0675f5d3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e17d3cc5e1de</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Chandralekha S]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 15:44:07 GMT</pubDate>
            <atom:updated>2023-03-15T15:44:07.717Z</atom:updated>
            <content:encoded><![CDATA[<p>JavaScript has come a long way since its inception and has become a ubiquitous language for web development. With the introduction of ES6, JavaScript has been equipped with some of the most powerful and flexible features that have taken the language to new heights. One such feature is the introduction of <strong>async/await</strong>. So here we will explore what async/await is how it compares with Fetch and when and how to use it.</p><p><strong>What is async/await?</strong></p><p>Async/await is introduced in ES8 (also known as ES2017) that simplifies asynchronous code. It is a syntactic sugar built on top of promises that makes it easier to write and reason about asynchronous code. Async/await allows you to write asynchronous code that looks and behaves like synchronous code, making it easier to read and write.</p><p>Async/await works by using the async keyword to mark a function as asynchronous, and the await keyword to pause the execution of a function until a promise is resolved.</p><pre>async function fetchUserData() {<br>  const response = await fetch(&#39;https://api.example.com/user&#39;);<br>  const data = await response.json();<br>  return data;<br>}<br><br>fetchUserData()<br>  .then(data =&gt; console.log(data))<br>  .catch(error =&gt; console.error(error));</pre><p>In this example, fetchUserData() is marked as async, which means it returns a promise that resolves to the data returned by the fetch call. The await keyword is used to pause the execution of the function until the fetch call resolves, and then again until the response.json() call resolves.</p><p><strong>How does async/await compare with Fetch?</strong></p><p>Fetch is a built-in browser API for making HTTP requests. It returns a promise that resolves to the response object, which contains information about the response, such as headers and status code, as well as the response body.</p><p>Fetch is great for making asynchronous HTTP requests, but it can be a bit verbose to work with, especially when handling errors. Here’s an example:</p><pre>fetch(&#39;https://api.example.com/user&#39;)<br>  .then(response =&gt; {<br>    if (!response.ok) {<br>      throw new Error(&#39;Network response was not ok&#39;);<br>    }<br>    return response.json();<br>  })<br>  .then(data =&gt; console.log(data))<br>  .catch(error =&gt; console.error(error));</pre><p>In this example, we check if the response was successful using the ok property of the response object, and if it&#39;s not, we throw an error. This adds a bit of complexity to the code, and can make it harder to read and reason about.</p><p>Async/await simplifies this code by allowing us to handle errors using try and catch statements, like this:</p><pre>async function fetchUserData() {<br>  try {<br>    const response = await fetch(&#39;https://api.example.com/user&#39;);<br>    if (!response.ok) {<br>      throw new Error(&#39;Network response was not ok&#39;);<br>    }<br>    const data = await response.json();<br>    return data;<br>  } catch (error) {<br>    console.error(error);<br>  }<br>}<br><br>fetchUserData();</pre><p>In this example, we use try and catch to handle errors, which makes the code easier to read and reason about.</p><p><strong>When and how to use async/await?</strong></p><p>Async/await should be used when working with asynchronous code that returns promises. It makes the code easier to read and reason about, and simplifies error handling. Here are some tips on how to use async/await effectively:</p><ol><li>Always mark asynchronous functions with the async keyword.</li><li>Use await to pause the execution of the function until a promise is resolved.</li><li>Handle errors using try and catch.</li><li>Use Promise.all to execute multiple asynchronous operations in parallel.</li><li>Avoid mixing async/await and .then/.catch syntax in the same code block, as it can lead to confusion and make the code harder to read.</li></ol><p>Parallelism in JavaScript refers to the ability to perform multiple tasks simultaneously, without blocking the main thread. Parallelism can be achieved in JavaScript through techniques such as using web workers, using the Promise.all method to execute multiple Promises in parallel, or using the await keyword to wait for multiple Promises to resolve simultaneously.</p><p>Here’s an example of using Promise.all with async/await:</p><pre>async function fetchData() {<br>  const [userData, postList] = await Promise.all([<br>    fetch(&#39;https://api.example.com/user&#39;),<br>    fetch(&#39;https://api.example.com/posts&#39;)<br>  ]);<br><br>  const userDataJson = await userData.json();<br>  const postListJson = await postList.json();<br><br>  return {<br>    user: userDataJson,<br>    posts: postListJson<br>  };<br>}<br><br>fetchData()<br>  .then(data =&gt; console.log(data))<br>  .catch(error =&gt; console.error(error));</pre><p>In this example, we use Promise.all to fetch data from two different endpoints in parallel, which can improve performance by reducing the total time it takes to fetch the data.</p><p><strong>How can async/await improve performance?</strong></p><p>Async/await can improve performance by allowing asynchronous operations to be executed in parallel, without blocking the main thread. This can lead to faster execution times and a better user experience.</p><p>Async/await can also simplify error handling, which can reduce the likelihood of errors going unnoticed and causing problems down the line.</p><p><strong>How should async/await not be used?</strong></p><p>Async/await should not be used to block the main thread with long-running operations. Since JavaScript runs on a single thread, blocking the main thread can cause the page to become unresponsive and negatively impact the user experience.</p><p>Async/await should also not be used as a replacement for promises in all cases. Promises provide more flexibility and can be used in situations where async/await is not applicable or does not provide any benefits.</p><p><strong>Conclusion</strong></p><p>Async/await is a powerful feature of modern JavaScript that simplifies asynchronous code and improves readability and error handling. When used correctly, async/await can improve performance and provide a better user experience. However, it’s important to use async/await appropriately and avoid common pitfalls to ensure that it doesn’t negatively impact performance or introduce bugs into the code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e17d3cc5e1de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Essential JavaScript Design Patterns]]></title>
            <link>https://medium.com/@chandralekha-selvam/mastering-essential-javascript-design-patterns-6e14fe0fae92?source=rss-7f0675f5d3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e14fe0fae92</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Chandralekha S]]></dc:creator>
            <pubDate>Tue, 14 Mar 2023 11:15:22 GMT</pubDate>
            <atom:updated>2023-03-14T11:15:22.776Z</atom:updated>
            <content:encoded><![CDATA[<p>JavaScript is a powerful language that allows developers to create dynamic and interactive web applications. However, as applications become more complex, it’s important to follow good design patterns to ensure code maintainability, scalability, and readability. In this blog post, we will discuss some important JavaScript design patterns that every JavaScript developer should know.</p><ol><li><strong>Singleton Pattern</strong>: The Singleton pattern ensures that only one instance of a class exists throughout the application. This pattern is useful when we need to create a single instance of an object that is used across different parts of the application.</li></ol><pre>let instance = null;<br><br>class MyClass {<br>  constructor() {<br>    if (!instance) {<br>      instance = this;<br>    }<br><br>    return instance;<br>  }<br>}<br><br>const obj1 = new MyClass();<br>const obj2 = new MyClass();<br><br>console.log(obj1 === obj2); // true</pre><p>2. <strong>Module Pattern</strong>: The Module pattern is a way of encapsulating code into a self-contained module. This pattern allows developers to keep code organised and reduces the chances of naming conflicts.</p><pre>const module = (function() {<br>  let privateVariable = 0;<br><br>  function privateMethod() {<br>    return privateVariable++;<br>  }<br><br>  return {<br>    publicMethod: function() {<br>      return privateMethod();<br>    }<br>  };<br>})();<br><br>console.log(module.publicMethod()); // 0<br>console.log(module.publicMethod()); // 1</pre><p>3. <strong>Factory Pattern</strong>: The Factory pattern is a way of creating objects without specifying the exact class of the object that will be created. This pattern is useful when we need to create multiple objects that have similar properties.</p><pre>class Car {<br>  constructor(options) {<br>    this.model = options.model;<br>    this.color = options.color;<br>    this.engine = options.engine;<br>  }<br>}<br><br>class CarFactory {<br>  createCar(options) {<br>    return new Car(options);<br>  }<br>}<br><br>const factory = new CarFactory();<br>const car1 = factory.createCar({ model: &#39;Tesla&#39;, color: &#39;Red&#39;, engine: &#39;Electric&#39; });<br>const car2 = factory.createCar({ model: &#39;Audi&#39;, color: &#39;Black&#39;, engine: &#39;Gasoline&#39; });</pre><p>4. <strong>Observer Pattern</strong>: The Observer pattern is a way of notifying objects about changes in the state of another object. This pattern is useful when we need to keep different parts of the application in sync with each other.</p><pre>class Subject {<br>  constructor() {<br>    this.observers = [];<br>  }<br><br>  addObserver(observer) {<br>    this.observers.push(observer);<br>  }<br><br>  removeObserver(observer) {<br>    this.observers = this.observers.filter(obs =&gt; obs !== observer);<br>  }<br><br>  notify(data) {<br>    this.observers.forEach(observer =&gt; observer.update(data));<br>  }<br>}<br><br>class Observer {<br>  update(data) {<br>    console.log(`Received data: ${data}`);<br>  }<br>}<br><br>const subject = new Subject();<br>const observer1 = new Observer();<br>const observer2 = new Observer();<br><br>subject.addObserver(observer1);<br>subject.addObserver(observer2);<br>subject.notify(&#39;Hello, world!&#39;);</pre><p>5. <strong>Prototype Pattern</strong>: The Prototype pattern is a way of creating new objects by cloning existing objects. This pattern is useful when we need to create many similar objects.</p><pre>const carPrototype = {<br>  model: &#39;Unknown&#39;,<br>  color: &#39;Unknown&#39;,<br>  engine: &#39;Unknown&#39;,<br><br>  clone() {<br>    return Object.create(this);<br>  }<br>};<br><br>const car1 = carPrototype.clone();<br>car1.model = &#39;Tesla&#39;;<br>car1.color = &#39;Red&#39;;<br>car1.engine = &#39;Electric&#39;;<br><br>const car2 = carPrototype.clone();<br>car2.model = &#39;Audi&#39;;<br>car2.color = &#39;Black&#39;;<br>car2.engine = &#39;Gasoline&#39;;</pre><p>In conclusion, these design patterns are essential for building scalable, maintainable, and readable JavaScript applications. They can help solve common programming problems, improve code organisation, and reduce bugs and errors.</p><p>By mastering these patterns, developers can write code that is modular, reusable, and efficient. They can also create applications that are easier to maintain and extend, and that can adapt to changing requirements and environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e14fe0fae92" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>