<?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 Muyiwa Johnson on Medium]]></title>
        <description><![CDATA[Stories by Muyiwa Johnson on Medium]]></description>
        <link>https://medium.com/@muyiwamighty?source=rss-7a196e6b70bb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fjd8-Zmi9ryTm6BwYBzdCg.jpeg</url>
            <title>Stories by Muyiwa Johnson on Medium</title>
            <link>https://medium.com/@muyiwamighty?source=rss-7a196e6b70bb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 12:42:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@muyiwamighty/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[Web Workers Tutorial: Build a High-Performance Spreadsheet with TypeScript — PHASE 1: The Problem…]]></title>
            <link>https://medium.com/@muyiwamighty/web-workers-tutorial-build-a-high-performance-spreadsheet-with-typescript-phase-1-the-problem-7abbbdc980ce?source=rss-7a196e6b70bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/7abbbdc980ce</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[webworker]]></category>
            <dc:creator><![CDATA[Muyiwa Johnson]]></dc:creator>
            <pubDate>Sat, 27 Dec 2025 08:57:27 GMT</pubDate>
            <atom:updated>2025-12-27T08:57:27.870Z</atom:updated>
            <content:encoded><![CDATA[<h3>Web Workers Tutorial: Build a High-Performance Spreadsheet with TypeScript — PHASE 1: The Problem with the Main Thread</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pbv9FrnjtcY8KPIcbm8mRw.png" /></figure><p>In this phase, we’ll experience the problem that Web Workers solve: <strong>the blocking main thread</strong>. You’ll build a simple spreadsheet that freezes when performing heavy calculations, demonstrating exactly why Web Workers are essential.</p><h3>Table of contents</h3><h3><strong>Learning Objectives</strong></h3><p>What you will learn in this phase:</p><ul><li>Understand JavaScript’s single-threaded nature</li><li>Experience UI freezing with heavy computations</li><li>See the performance problem firsthand</li><li>Understand why Web Workers are the solution</li></ul><h3><strong>What You’ll Build</strong></h3><p>A simple spreadsheet application that:</p><ul><li>Displays a grid of cells</li><li>Allows entering numbers and formulas</li><li>Calculates formulas (SUM, AVERAGE)</li><li><strong>Freezes the UI</strong> when processing large datasets</li></ul><h3><strong>Understanding the Problem</strong></h3><h4><strong>JavaScript’s Single Thread</strong></h4><p>JavaScript runs on a <strong>single main thread</strong>. By default, the browser uses this single thread to run all the JavaScript in your page, as well as to perform layout, reflows, and garbage collection. This means that long-running JavaScript functions can block the thread, leading to an unresponsive page and a bad user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CSeN_fnY_0XwFJyDQz0qcA.png" /></figure><p><strong>The Problem: </strong>When JavaScript is executing heavy code, everything else stops:</p><ul><li>UI can’t update</li><li>User clicks are ignored</li><li>Animations freeze</li><li>Page becomes unresponsive</li></ul><h4><strong>What Happens Without Web Workers</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-LPliCei3l-v8AHAfqdKw.png" /></figure><h3><strong>Building the Problem Demo</strong></h3><p>Let’s build a spreadsheet that demonstrates this problem.</p><h4><strong>Step 1: Project Setup</strong></h4><p>We’ll be adding new files to the structure you created in Prerequisites:</p><pre>learn-web-workers/<br>├── src/<br>│   ├── main.ts          # Already created in Prerequisites<br>│   ├── spreadsheet.ts   # New - we&#39;ll create this<br>│   └── styles.css       # New - we&#39;ll create this<br>├── index.html           # Already created in Prerequisites<br>├── package.json<br>└── tsconfig.json</pre><h4><strong>Step 2: Update HTML Structure</strong></h4><p>Update the existing index.html in the project root with the spreadsheet content:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>    &lt;title&gt;Spreadsheet - The Problem&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;./src/styles.css&quot; /&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div class=&quot;container&quot;&gt;<br>      &lt;header&gt;<br>        &lt;h1&gt;📊 Spreadsheet Demo&lt;/h1&gt;<br>        &lt;p class=&quot;subtitle&quot;&gt;<br>          Watch what happens when we calculate without Web Workers<br>        &lt;/p&gt;<br>      &lt;/header&gt;<br><br>      &lt;div class=&quot;controls&quot;&gt;<br>        &lt;button id=&quot;generateData&quot;&gt;Generate 10,000 Rows&lt;/button&gt;<br>        &lt;button id=&quot;calculateAll&quot;&gt;Calculate All Formulas&lt;/button&gt;<br>        &lt;div class=&quot;status&quot; id=&quot;status&quot;&gt;Ready&lt;/div&gt;<br>      &lt;/div&gt;<br><br>      &lt;div class=&quot;spreadsheet-container&quot;&gt;<br>        &lt;div id=&quot;spreadsheet&quot;&gt;&lt;/div&gt;<br>      &lt;/div&gt;<br><br>      &lt;div class=&quot;info&quot;&gt;<br>        &lt;h3&gt;⚠️ The Problem&lt;/h3&gt;<br>        &lt;p&gt;<br>          Click &quot;Calculate All Formulas&quot; and try to interact with the page.<br>          Notice how:<br>        &lt;/p&gt;<br>        &lt;ul&gt;<br>          &lt;li&gt;The UI freezes completely&lt;/li&gt;<br>          &lt;li&gt;You can&#39;t click anything&lt;/li&gt;<br>          &lt;li&gt;The page appears &quot;broken&quot;&lt;/li&gt;<br>          &lt;li&gt;This is the problem Web Workers solve!&lt;/li&gt;<br>        &lt;/ul&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br><br>    &lt;script type=&quot;module&quot; src=&quot;./src/main.ts&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>Note</strong>: We’re updating the existing index.html from Prerequisites. The script path is ./src/main.ts because index.html is in the project root.</p><h4><strong>Step 3: CSS Styling</strong></h4><p>Create src/styles.css:</p><pre>* {<br>  margin: 0;<br>  padding: 0;<br>  box-sizing: border-box;<br>}<br><br>body {<br>  font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, Roboto, Oxygen,<br>    Ubuntu, Cantarell, sans-serif;<br>  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);<br>  min-height: 100vh;<br>  padding: 20px;<br>}<br><br>.container {<br>  max-width: 1200px;<br>  margin: 0 auto;<br>  background: white;<br>  border-radius: 12px;<br>  padding: 30px;<br>  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);<br>}<br><br>header {<br>  text-align: center;<br>  margin-bottom: 30px;<br>}<br><br>header h1 {<br>  color: #333;<br>  font-size: 2.5em;<br>  margin-bottom: 10px;<br>}<br><br>.subtitle {<br>  color: #666;<br>  font-size: 1.1em;<br>}<br><br>.controls {<br>  display: flex;<br>  gap: 15px;<br>  align-items: center;<br>  margin-bottom: 20px;<br>  padding: 20px;<br>  background: #f8f9fa;<br>  border-radius: 8px;<br>}<br><br>button {<br>  padding: 12px 24px;<br>  font-size: 16px;<br>  border: none;<br>  border-radius: 6px;<br>  cursor: pointer;<br>  font-weight: 600;<br>  transition: all 0.3s;<br>}<br><br>button:hover {<br>  transform: translateY(-2px);<br>  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);<br>}<br><br>button:active {<br>  transform: translateY(0);<br>}<br><br>#generateData {<br>  background: #4caf50;<br>  color: white;<br>}<br><br>#calculateAll {<br>  background: #f44336;<br>  color: white;<br>}<br><br>.status {<br>  margin-left: auto;<br>  padding: 12px 20px;<br>  background: #2196f3;<br>  color: white;<br>  border-radius: 6px;<br>  font-weight: 600;<br>}<br><br>.spreadsheet-container {<br>  border: 2px solid #ddd;<br>  border-radius: 8px;<br>  overflow: auto;<br>  max-height: 500px;<br>  margin-bottom: 20px;<br>}<br><br>#spreadsheet {<br>  display: grid;<br>  grid-template-columns: 60px repeat(10, 100px);<br>  gap: 1px;<br>  background: #ddd;<br>}<br><br>.cell {<br>  background: white;<br>  padding: 8px;<br>  min-height: 30px;<br>  display: flex;<br>  align-items: center;<br>  font-size: 14px;<br>}<br><br>.cell-header {<br>  background: #4caf50;<br>  color: white;<br>  font-weight: bold;<br>  justify-content: center;<br>}<br><br>.cell-input {<br>  width: 100%;<br>  border: none;<br>  outline: none;<br>  font-size: 14px;<br>  padding: 4px;<br>}<br><br>.info {<br>  background: #fff3cd;<br>  border: 2px solid #ffc107;<br>  border-radius: 8px;<br>  padding: 20px;<br>}<br><br>.info h3 {<br>  color: #856404;<br>  margin-bottom: 10px;<br>}<br><br>.info ul {<br>  margin-left: 20px;<br>  color: #856404;<br>}<br><br>.info li {<br>  margin: 5px 0;<br>}</pre><h4><strong>Step 4: Spreadsheet Logic</strong></h4><p>Create src/spreadsheet.ts:</p><pre>interface Cell {<br>  value: string;<br>  formula?: string;<br>  calculated?: number;<br>}<br><br>export class Spreadsheet {<br>  private grid: Cell[][] = [];<br>  private rows: number = 100;<br>  private cols: number = 10;<br>  private container: HTMLElement;<br><br>  constructor(containerId: string) {<br>    this.container = document.getElementById(containerId)!;<br>    this.initializeGrid();<br>    this.render();<br>  }<br><br>  private initializeGrid(): void {<br>    this.grid = [];<br>    for (let row = 0; row &lt; this.rows; row++) {<br>      this.grid[row] = [];<br>      for (let col = 0; col &lt; this.cols; col++) {<br>        this.grid[row][col] = { value: &quot;&quot; };<br>      }<br>    }<br>  }<br><br>  private render(): void {<br>    this.container.innerHTML = &quot;&quot;;<br>    this.container.style.gridTemplateColumns = `60px repeat(${this.cols}, 100px)`;<br><br>    // Header row<br>    const headerRow = document.createElement(&quot;div&quot;);<br>    headerRow.className = &quot;cell cell-header&quot;;<br>    headerRow.textContent = &quot;&quot;;<br>    this.container.appendChild(headerRow);<br><br>    for (let col = 0; col &lt; this.cols; col++) {<br>      const header = document.createElement(&quot;div&quot;);<br>      header.className = &quot;cell cell-header&quot;;<br>      header.textContent = String.fromCharCode(65 + col); // A, B, C...<br>      this.container.appendChild(header);<br>    }<br><br>    // Data rows<br>    for (let row = 0; row &lt; this.rows; row++) {<br>      const rowHeader = document.createElement(&quot;div&quot;);<br>      rowHeader.className = &quot;cell cell-header&quot;;<br>      rowHeader.textContent = (row + 1).toString();<br>      this.container.appendChild(rowHeader);<br><br>      for (let col = 0; col &lt; this.cols; col++) {<br>        const cell = document.createElement(&quot;div&quot;);<br>        cell.className = &quot;cell&quot;;<br><br>        const input = document.createElement(&quot;input&quot;);<br>        input.className = &quot;cell-input&quot;;<br>        input.type = &quot;text&quot;;<br>        input.value = this.grid[row][col].value;<br>        input.dataset.row = row.toString();<br>        input.dataset.col = col.toString();<br><br>        input.addEventListener(&quot;input&quot;, (e) =&gt; {<br>          const target = e.target as HTMLInputElement;<br>          const row = parseInt(target.dataset.row!);<br>          const col = parseInt(target.dataset.col!);<br>          this.grid[row][col].value = target.value;<br>        });<br><br>        cell.appendChild(input);<br>        this.container.appendChild(cell);<br>      }<br>    }<br>  }<br><br>  // Generate random data<br>  public generateData(count: number = 10000): void {<br>    const startTime = performance.now();<br><br>    for (let i = 0; i &lt; count; i++) {<br>      const row = Math.floor(Math.random() * this.rows);<br>      const col = Math.floor(Math.random() * this.cols);<br>      this.grid[row][col].value = Math.floor(Math.random() * 1000).toString();<br>    }<br><br>    const endTime = performance.now();<br>    this.updateStatus(<br>      `Generated ${count} values in ${(endTime - startTime).toFixed(2)}ms`<br>    );<br>    this.render();<br>  }<br><br>  // Calculate all formulas (BLOCKS MAIN THREAD)<br>  public calculateAll(): void {<br>    const startTime = performance.now();<br>    this.updateStatus(&quot;Calculating... (UI is frozen!)&quot;);<br><br>    // Simulate heavy calculation<br>    let sum = 0;<br>    for (let row = 0; row &lt; this.rows; row++) {<br>      for (let col = 0; col &lt; this.cols; col++) {<br>        const cell = this.grid[row][col];<br><br>        // If it&#39;s a number, add to sum<br>        const num = parseFloat(cell.value);<br>        if (!isNaN(num)) {<br>          sum += num;<br>        }<br><br>        // Heavy computation to simulate real-world scenario<br>        // Increased iterations for powerful hardware (M4, M3, etc.)<br>        for (let i = 0; i &lt; 500000; i++) {<br>          Math.sqrt(Math.random() * 1000);<br>        }<br>      }<br>    }<br><br>    const endTime = performance.now();<br>    const duration = (endTime - startTime).toFixed(2);<br><br>    this.updateStatus(`Calculated in ${duration}ms (UI was frozen!)`);<br><br>    // Try to show alert - this will be delayed!<br>      setTimeout(() =&gt; {<br>        alert(<br>          `Calculation complete! Sum: ${sum.toFixed(<br>            2<br>          )}\n\nNotice how the UI was frozen during calculation.`<br>        );<br>      }, 100);<br>  }<br><br>  private updateStatus(message: string): void {<br>    const status = document.getElementById(&quot;status&quot;);<br>    if (status) {<br>      status.textContent = message;<br>    }<br>  }<br>}</pre><h4><strong>Step 5: Update Main Entry Point</strong></h4><p>Update the existing src/main.ts (created in Prerequisites):</p><pre>import { Spreadsheet } from &quot;./spreadsheet&quot;;<br><br>// Initialize spreadsheet<br>const spreadsheet = new Spreadsheet(&quot;spreadsheet&quot;);<br><br>// Generate data button<br>document.getElementById(&quot;generateData&quot;)?.addEventListener(&quot;click&quot;, () =&gt; {<br>  spreadsheet.generateData(50000);<br>});<br><br>// Calculate all button<br>document.getElementById(&quot;calculateAll&quot;)?.addEventListener(&quot;click&quot;, () =&gt; {<br>  spreadsheet.calculateAll();<br>});<br><br>console.log(<br>  &#39;Spreadsheet loaded. Try clicking &quot;Calculate All Formulas&quot; and watch the UI freeze!&#39;<br>);</pre><h4><strong>Step 6: Verify package.json</strong></h4><p>Your package.json should already have these scripts (from Prerequisites):</p><pre>{<br>  &quot;name&quot;: &quot;learn-web-workers&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;vite&quot;,<br>    &quot;build&quot;: &quot;tsc &amp;&amp; vite build&quot;,<br>    &quot;preview&quot;: &quot;vite preview&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;typescript&quot;: &quot;^5.0.0&quot;,<br>    &quot;vite&quot;: &quot;^5.0.0&quot;,<br>    &quot;@types/node&quot;: &quot;^20.0.0&quot;<br>  }<br>}</pre><h4><strong>Step 7: Run the Demo</strong></h4><p>If you haven’t already, start the dev server:</p><pre>npm run dev</pre><p>The browser should open automatically, or navigate to http://localhost:5173.</p><h3><strong>Testing the Problem</strong></h3><ol><li><strong>Click “Generate 50,000 Rows”</strong> — This should be fast</li><li><strong>Click “Calculate All Formulas”</strong> — Watch what happens:</li></ol><ul><li>The status says “Calculating…”</li><li><strong>Try clicking other buttons</strong> — They don’t work!</li><li><strong>Try scrolling</strong>— The page is frozen!</li><li><strong>Try typing</strong> — Nothing responds!</li></ul><p>This is the <strong>blocking main thread problem</strong></p><h3><strong>Understanding What Happened</strong></h3><h4><strong>The Main Thread Timeline</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*61I_5cW3zrB69ny1mBR-Fg.png" /></figure><p><strong>Timeline Breakdown:</strong></p><ul><li>0–10ms — UI updates to show “Calculating…”</li><li>10–5000ms — Heavy calculation runs (UI completely frozen)</li><li>5000–5010ms — UI updates with results</li><li>After 5010ms — Page becomes responsive again</li></ul><p><strong>Key Points:</strong></p><ul><li>Main thread is busy with calculation</li><li>UI can’t update during calculation</li><li>User interactions are queued but not processed</li><li>Page appears “broken” to users</li></ul><h4><strong>Why This Happens</strong></h4><p>JavaScript’s event loop processes tasks one at a time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yc8-spXloDkye0G1zyiapQ.png" /></figure><p><strong>The Problem:</strong></p><ul><li>Heavy calculation blocks the event loop</li><li>Events queue up but aren’t processed</li><li>UI can’t update</li><li>User sees a frozen page</li></ul><h3>Checkpoint</h3><p>Before moving to <strong>Phase 2</strong>, make sure you:</p><ul><li>Understand that JavaScript runs on a single main thread</li><li>Have experienced UI freezing with heavy calculations</li><li>Understand why this is a problem for user experience</li><li>Can explain what “blocking the main thread” means</li></ul><h3>Key Takeaways</h3><ul><li>JavaScript is single-threaded — One thread handles everything</li><li>Heavy code blocks the UI — When JavaScript runs, UI stops</li><li>Users experience freezing — Page becomes unresponsive</li><li>This is a real problem — Happens in production apps</li><li>Web Workers solve this — Run code in separate threads</li></ul><h3><strong>Exercise</strong></h3><p>Try modifying the code to make it even slower:</p><p>1. Increase the loop iterations in `calculateAll()` (currently 500,000 per cell)</p><p>2. Add more complex calculations</p><p>3. Process more data</p><p>4. Notice how the freezing gets worse</p><p><strong>Note for Powerful Hardware:<br></strong>If you’re using a powerful machine (M4, M3, high-end Intel/AMD), you might need to increase the iterations even more. The code uses 500,000 iterations per cell, which should cause noticeable freezing even on high-end hardware. If it still doesn’t freeze enough, try 1,000,000 or more.</p><h3>References</h3><ul><li>MDN: Concurrency model and Event Loop — <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop">developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop</a></li><li><a href="https://javascript.info/">JavaScript.info</a>: Event Loop — <a href="https://javascript.info/event-loop">javascript.info/event-loop</a></li><li><a href="https://web.dev/">Web.dev</a>: Main Thread — <a href="https://web.dev/main-thread">web.dev/main-thread</a></li></ul><h3>What’s Next?</h3><p>In Phase 2, we’ll learn about Web Workers and how they solve this exact problem. You’ll see the same spreadsheet, but this time the UI stays responsive!</p><p>Ready? Let’s move to <a href="#"><strong>Phase 2: Web Workers Basics</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7abbbdc980ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Workers Tutorial: Build a High-Performance Spreadsheet App with TypeScript]]></title>
            <link>https://medium.com/@muyiwamighty/web-workers-tutorial-build-a-high-performance-spreadsheet-app-with-typescript-3edadf72a714?source=rss-7a196e6b70bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3edadf72a714</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[webworker]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Muyiwa Johnson]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 06:10:13 GMT</pubDate>
            <atom:updated>2025-12-26T06:10:13.774Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aF5_uHFws4U7m8GaWVESFw.png" /></figure><p>Hi and welcome to the most comprehensive <strong>Web Workers</strong> tutorial! This step-by-step guide will teach you Web Workers from the ground up by building a real <strong>spreadsheet application</strong>. You’ll learn <em>when</em> and <em>why</em> Web Workers are essential, and how they solve performance problems in web applications.</p><h4><strong>Learning Path</strong></h4><pre>[Start Here] → [Prerequisites] → [Phase 1: Problem] → [Phase 2: Basics]<br>     ↓<br>[Phase 3: Foundation] → [Phase 4: Engine] → [Phase 5: Advanced] → [Phase 6: Performance]<br>     ↓<br>[Phase 7: Features] → [Phase 8: Production] → [🎉 Master!]</pre><p>Follow this paths in order:</p><ol><li><strong>Prerequisites: </strong>What you need before starting</li><li><strong>Phase 1: The Problem</strong> — Demonstrate the blocking main thread problem</li><li><strong>Phase 2: Web Workers Basics</strong> — Web Workers fundamentals.</li><li><strong>Phase 3: Spreadsheet Foundation</strong> — Build spreadsheet foundation, grid, cells</li><li><strong>Phase 4: Formula Engine</strong> — Formula parser and evaluator in workers</li><li><strong>Phase 5: Advanced Workers</strong> — Shared workers, worker pools, task queues</li><li><strong>Phase 6: Performance</strong> — Optimization, profiling, virtual scrolling</li><li><strong>Phase 7: Real Features</strong> — Sorting, filtering, import/export, charts</li><li><strong>Phase 8: Production </strong>— Build configuration, bundling, deployment</li></ol><h4><strong>What Makes This Tutorial Special</strong></h4><p><strong>Visual Learning</strong></p><ul><li><strong>Architecture diagrams</strong> showing how Web Workers work</li><li><strong>Flow charts</strong> for worker communication patterns</li><li><strong>Performance comparisons</strong> showing before/after</li><li><strong>Sequence diagrams</strong> for complex worker interactions</li></ul><p><strong>Deep Explanations</strong></p><ul><li><strong>Why we do this</strong> sections explaining design decisions</li><li><strong>Best practices</strong> callouts throughout</li><li><strong>Common mistakes</strong> and how to avoid them</li><li><strong>MDN documentation</strong> references for deeper learnin</li></ul><p><strong>Complete Code Examples</strong></p><ul><li><strong>Complete file contents </strong>when creating new files</li><li><strong>Incremental changes</strong> showing what to add/modify</li><li><strong>Highlighted important sections</strong> with explanations</li><li><strong>Working examples</strong> you can run immediately</li></ul><h4><strong>What You’ll Build</strong></h4><ul><li>Here is a complete spreadsheet application with:</li><li>Grid with cells — A1, B2 notation like Excel</li><li>Formula support — SUM, AVERAGE, COUNT, and custom formulas</li><li>Cell references — A1+B1, SUM(A1:A10)</li><li>Real-time calculations — All done in Web Workers</li><li>Large dataset handling — 10,000+ rows without freezing</li><li>Sorting and filtering — Worker-based operations</li><li>Data import/export — CSV, JSON support</li><li>Undo/Redo — Full history management</li><li>Performance optimizations — Virtual scrolling, memoization</li></ul><h4><strong>Prerequisites</strong></h4><p>Before starting, you should have:</p><ul><li>JavaScript fundamentals — variables, functions, arrays, objects</li><li>TypeScript basics — types, interfaces, classes (we’ll cover this)</li><li>HTML/CSS basics — helpful but not required</li><li>Node.js installed — for build tools</li><li>Text editor or IDE — VS Code recommended</li></ul><h4><strong>Learning Approach</strong></h4><ul><li>See the problem — Experience UI freezing firsthand</li><li>Understand the solution — Learn why Web Workers solve it</li><li>Build incrementally — Add features progressively</li><li>Measure performance — See the improvements</li></ul><h4>Getting Help</h4><h4>Notes</h4><ul><li>This tutorial uses TypeScript for type safety</li><li>Code examples are tested and working</li><li>Best practices are based on web standards</li><li>Performance considerations are included throughout</li></ul><h4><strong>Ready to Start?</strong></h4><p>Begin with <a href="https://medium.com/@muyiwamighty/web-workers-tutorial-build-a-high-performance-spreadsheet-with-typescript-phase-0-prerequisites-9b8f86bc24a0"><strong>prerequisites</strong></a> to set up your environment, then proceed to <strong>Phase 1: The Problem</strong>.</p><p>Happy learning! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3edadf72a714" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Workers Tutorial: Build a High-Performance Spreadsheet with TypeScript — PHASE 0: Prerequisites]]></title>
            <link>https://medium.com/@muyiwamighty/web-workers-tutorial-build-a-high-performance-spreadsheet-with-typescript-phase-0-prerequisites-9b8f86bc24a0?source=rss-7a196e6b70bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b8f86bc24a0</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[webworker]]></category>
            <dc:creator><![CDATA[Muyiwa Johnson]]></dc:creator>
            <pubDate>Thu, 25 Dec 2025 09:45:06 GMT</pubDate>
            <atom:updated>2025-12-26T06:09:52.042Z</atom:updated>
            <content:encoded><![CDATA[<h3>Web Workers Tutorial: Build a High-Performance Spreadsheet with TypeScript — PHASE 0: Prerequisites</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tvuv8fNZRZ6Wc72Ep5AbBA.png" /></figure><p>Before diving into Web Workers, let’s make sure you have everything set up correctly. This guide will help you prepare your development environment and understand the foundational concepts.</p><h3>Table of contents</h3><p>· <a href="#f441">What You Need</a><br> ∘ <a href="#4536">1. Node.js and npm</a><br> ∘ <a href="#0d97">2. TypeScript</a><br> ∘ <a href="#6b76">3. Text Editor or IDE</a><br> ∘ <a href="#beb8">4. Modern Web Browser</a><br> ∘ <a href="#73ce">5. Basic JavaScript Knowledge</a><br> ∘ <a href="#d68f">6. Basic HTML/CSS</a><br> ∘ <a href="#ed32">7. Terminal/Command Line</a><br> ∘ <a href="#397b">8. Git (Optional but Recommended)</a><br>· <a href="#d94e">JavaScript Concepts You Should Know</a><br> ∘ <a href="#4886">1. Event Loop and Asynchronous Code</a><br> ∘ <a href="#dfd5">2. Closures</a><br> ∘ <a href="#da54">3. Modules (ES6)</a><br> ∘ <a href="#06c7">4. Classes and Objects</a><br>· <a href="#8d83">TypeScript Basics (We’ll Cover This)</a><br> ∘ <a href="#7585">Basic Types</a><br> ∘ <a href="#6a49">Functions</a><br> ∘ <a href="#0404">Classes</a><br>· <a href="#85ce">Setting Up Your Development Environment</a><br> ∘ <a href="#5ef1">Step 1: Create Project Directory</a><br> ∘ <a href="#c28d">Step 2: Initialize npm Project</a><br> ∘ <a href="#3aa5">Step 3: Install TypeScript</a><br> ∘ <a href="#f5bf">Step 4: Create TypeScript Config</a><br> ∘ <a href="#da07">Step 5: Install Build Tool (Vite)</a><br> ∘ <a href="#2a64">Step 6: Update package.json Scripts</a><br> ∘ <a href="#7bbb">Step 7: Create Basic Project Structure</a><br> ∘ <a href="#384b">✅ Checklist</a><br> ∘ <a href="#da1d">What’s Next?</a><br> ∘ <a href="#6432">Additional Resources</a></p><h3><strong>What You Need</strong></h3><h4><strong>1. Node.js and npm</strong></h4><p>You’ll need Node.js to run build tools and manage dependencies:</p><pre>node --version<br># Should show: v18.x.x or higher<br><br>npm --version<br># Should show: 9.x.x or higher</pre><p><strong>If you don’t have Node.js:</strong></p><ul><li><strong>Download</strong>: <a href="https://nodejs.org/">nodejs.org</a></li><li><strong>macOS</strong>: brew install node</li><li><strong>Linux</strong>: sudo apt install nodejs npm (Ubuntu/Debian)</li></ul><p><strong>Why Node.js?</strong></p><ul><li>Run build tools (Vite, Webpack)</li><li>Manage dependencies with npm/pnpm</li><li>Run TypeScript compiler</li><li>Development server</li></ul><h4><strong>2. TypeScript</strong></h4><p>We’ll use TypeScript for type safety. Install it globally or in your project:</p><pre>npm install -g typescript<br>tsc --version<br># Should show: Version 5.x.x or higher</pre><p><strong>Why TypeScript?</strong></p><ul><li>Type safety catches errors early</li><li>Better IDE support and autocomplete</li><li>Makes code more maintainable</li><li>Industry standard for modern web development</li></ul><h4><strong>3. Text Editor or IDE</strong></h4><p>Choose one that you’re comfortable with:</p><p><strong>Recommended Options:</strong></p><ul><li><a href="http://code.visualstudio.com/">VS Code (Free)</a></li><li><a href="http://jetbrains.com/webstorm">WebStorm</a> (Free Enough)</li><li><a href="http://sublimetext.com/">Sublime Text (Free trial)</a></li></ul><p><strong>VS Code Extensions to Install:</strong></p><ul><li>TypeScript and JavaScript Language Features (built-in)</li><li>ESLint</li><li>Prettier</li></ul><h4><strong>4. Modern Web Browser</strong></h4><p><strong>Recommended Browsers:</strong></p><ul><li>Chrome/Edge (Chromium) — Best DevTools</li><li>Firefox — Excellent Web Workers support</li><li>Safari — Good support (macOS/iOS)</li></ul><p><strong>Check Web Workers Support:<br></strong>Open browser console and run:</p><pre>typeof Worker !== &quot;undefined&quot;;<br>// Should return: true</pre><h4><strong>5. Basic JavaScript Knowledge</strong></h4><p>You should be comfortable with:</p><p><strong>Essential JavaScript Concepts:</strong></p><pre>// Variables and types<br>const name = &quot;John&quot;;<br>let age = 25;<br>const isActive = true;<br><br>// Functions<br>function greet(name) {<br>  return `Hello, ${name}!`;<br>}<br><br>// Arrow functions<br>const add = (a, b) =&gt; a + b;<br><br>// Arrays<br>const numbers = [1, 2, 3];<br>numbers.forEach((n) =&gt; console.log(n));<br><br>// Objects<br>const person = {<br>  name: &quot;John&quot;,<br>  age: 25,<br>  greet() {<br>    return `Hi, I&#39;m ${this.name}`;<br>  },<br>};<br><br>// Promises and async/await<br>async function fetchData() {<br>  const response = await fetch(&quot;/api/data&quot;);<br>  return response.json();<br>}</pre><p><strong>If you need to brush up:</strong></p><ul><li><a href="http://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide">MDN JavaScript Guide</a></li><li><a href="https://javascript.info/">JavaScript.info</a></li></ul><h4><strong>6. Basic HTML/CSS</strong></h4><p>You should understand:</p><p><strong>HTML Basics:</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;My App&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;app&quot;&gt;&lt;/div&gt;<br>    &lt;script src=&quot;app.js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>CSS Basics:</strong></p><pre>.container {<br>  display: flex;<br>  padding: 20px;<br>  background-color: #f0f0f0;<br>}</pre><h4><strong>7. Terminal/Command Line</strong></h4><p>You’ll need to be comfortable with basic terminal commands:</p><p><strong>Essential Commands:</strong></p><pre><br># Navigate directories<br>cd /path/to/directory<br>cd ..              # Go up one directory<br>cd ~               # Go to home directory<br>pwd                # Show current directory<br><br># List files<br>ls                 # macOS/Linux<br>ls -la             # List all files including hidden<br>dir                # Windows<br><br># Create directories<br>mkdir myproject<br>mkdir -p src/components  # Create nested directories<br><br># Create files<br>touch file.js      # macOS/Linux<br>type nul &gt; file.js  # Windows<br><br># Run commands<br>npm run dev        # Start development server<br>npm install        # Install dependencies</pre><p><strong>If you’re new to terminal:</strong></p><ul><li>Practice basic navigation</li><li>Learn to run npm commands</li><li>Understand file paths</li></ul><h4><strong>8. Git (Optional but Recommended)</strong></h4><p>Version control is essential for real projects:</p><pre>git --version<br># Should show: git version 2.x.x or higher</pre><p><strong>If you don’t have Git</strong></p><ul><li>Download — <a href="https://git-scm.com/">git-scm.com</a></li><li>macOS — brew install git</li><li>Linux — sudo apt install git</li></ul><h3><strong>JavaScript Concepts You Should Know</strong></h3><h4><strong>1. Event Loop and Asynchronous Code</strong></h4><pre>console.log(&quot;1&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;2&quot;);<br>}, 0);<br><br>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;3&quot;);<br>});<br><br>console.log(&quot;4&quot;);<br>// Output: 1, 4, 3, 2</pre><p><strong>Why this matters:</strong></p><ul><li>Web Workers run in a separate thread</li><li>Understanding async helps understand worker communication</li></ul><h4><strong>2. Closures</strong></h4><p>Functions that remember their outer scope:</p><pre>function createCounter() {<br>  let count = 0;<br>  return function () {<br>    return ++count;<br>  };<br>}<br><br>const counter = createCounter();<br>console.log(counter()); // 1<br>console.log(counter()); // 2</pre><h4><strong>3. Modules (ES6)</strong></h4><p>Import/export syntax:</p><pre>// math.js<br>export function add(a, b) {<br>  return a + b;<br>}<br><br>export const PI = 3.14159;<br><br>// app.js<br>import { add, PI } from &quot;./math.js&quot;;</pre><p><strong>Why this matters:</strong></p><ul><li>Web Workers use modules</li><li>Modern JavaScript uses ES6 modules</li></ul><h4><strong>4. Classes and Objects</strong></h4><p>Object-oriented programming in JavaScript:</p><pre>class Calculator {<br>  constructor() {<br>    this.result = 0;<br>  }<br><br>  add(value) {<br>    this.result += value;<br>    return this;<br>  }<br><br>  getResult() {<br>    return this.result;<br>  }<br>}<br><br>const calc = new Calculator();<br>calc.add(5).add(3);<br>console.log(calc.getResult()); // 8</pre><h3><strong>TypeScript Basics (We’ll Cover This)</strong></h3><p>If you’re new to TypeScript, don’t worry, We’ll cover the basics, but here’s a quick preview:</p><h4><strong>Basic Types</strong></h4><pre>// Primitive types<br>const name: string = &quot;John&quot;;<br>const age: number = 25;<br>const isActive: boolean = true;<br><br>// Arrays<br>const numbers: number[] = [1, 2, 3];<br>const names: Array&lt;string&gt; = [&quot;John&quot;, &quot;Jane&quot;];<br><br>// Objects<br>interface Person {<br>  name: string;<br>  age: number;<br>  email?: string; // Optional property<br>}<br><br>const person: Person = {<br>  name: &quot;John&quot;,<br>  age: 25,<br>};</pre><h4><strong>Functions</strong></h4><pre>function greet(name: string): string {<br>  return `Hello, ${name}!`;<br>}<br><br>const add = (a: number, b: number): number =&gt; {<br>  return a + b;<br>};</pre><h4><strong>Classes</strong></h4><pre>class Calculator {<br>  private result: number = 0;<br><br>  add(value: number): Calculator {<br>    this.result += value;<br>    return this;<br>  }<br><br>  getResult(): number {<br>    return this.result;<br>  }<br>}</pre><p><strong>We’ll learn TypeScript as we go!</strong></p><h3><strong>Setting Up Your Development Environment</strong></h3><h4><strong>Step 1: Create Project Directory</strong></h4><pre>mkdir learn-web-workers<br>cd learn-web-workers</pre><h4><strong>Step 2: Initialize npm Project</strong></h4><pre>npm init -y</pre><p>This creates a package.json file.</p><h4><strong>Step 3: Install TypeScript</strong></h4><pre>npm install -D typescript @types/node</pre><h4><strong>Step 4: Create TypeScript Config</strong></h4><p>Generate tsconfig.json automatically</p><p>npx tsc --init</p><p>This creates a tsconfig.json with default settings. Then update it with our specific configuration:</p><p><strong>Update it with our specific configuration:</strong></p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;ES2020&quot;,<br>    &quot;module&quot;: &quot;ESNext&quot;,<br>    &quot;lib&quot;: [&quot;ES2020&quot;, &quot;DOM&quot;, &quot;WebWorker&quot;],<br>    &quot;outDir&quot;: &quot;./dist&quot;,<br>    &quot;rootDir&quot;: &quot;./src&quot;,<br>    &quot;strict&quot;: true,<br>    &quot;esModuleInterop&quot;: true,<br>    &quot;skipLibCheck&quot;: true,<br>    &quot;forceConsistentCasingInFileNames&quot;: true,<br>    &quot;moduleResolution&quot;: &quot;node&quot;,<br>    &quot;resolveJsonModule&quot;: true,<br>    &quot;isolatedModules&quot;: true,<br>    &quot;noEmit&quot;: true<br>  },<br>  &quot;include&quot;: [&quot;src/**/*&quot;],<br>  &quot;exclude&quot;: [&quot;node_modules&quot;]<br>}</pre><p>Why use tsc --init?</p><ul><li>Generates a complete config file automatically</li><li>Includes all available options with helpful comments</li><li>Shows recommended settings</li><li>Much easier than creating from scratch</li></ul><h4><strong>Step 5: Install Build Tool (Vite)</strong></h4><p>npm install -D vite</p><h4><strong>Step 6: Update package.json Scripts</strong></h4><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;vite&quot;,<br>    &quot;build&quot;: &quot;tsc &amp;&amp; vite build&quot;,<br>    &quot;preview&quot;: &quot;vite preview&quot;<br>  }<br>}</pre><h4><strong>Step 7: Create Basic Project Structure</strong></h4><pre>mkdir src<br>mkdir src/workers<br>touch index.html<br>touch src/main.ts</pre><p><strong>Your project structure:</strong></p><pre>learn-web-workers/<br>├── src/<br>│   ├── workers/<br>│   └── main.ts<br>├── index.html          # Vite entry point (in project root)<br>├── package.json<br>├── tsconfig.json<br>└── node_modules/</pre><p><strong>Important</strong>: index.html goes in the <strong>project root</strong>, not in src/. This is Vite’s default behavior — it automatically looks for index.html in the root directory.</p><h4><strong>✅ Checklist</strong></h4><p>Before starting Phase 1, make sure you have:</p><p>✓ Node.js installed (v18+)</p><p>✓ npm installed</p><p>✓ TypeScript installed</p><p>✓ VS Code (or preferred editor) installed</p><p>✓ Modern browser installed</p><p>✓ Basic JavaScript knowledge</p><p>✓ Terminal/command line comfort</p><p>✓ Project directory created</p><p>✓ TypeScript config created (tsconfig.json)</p><p>✓ Vite installed</p><p>✓ index.html created in project root</p><p>✓ Can run npm run dev successfully</p><h4><strong>What’s Next?</strong></h4><p>Once you’ve completed this setup:</p><ol><li><strong>Verify everything works:</strong></li></ol><pre>node --version<br>npm --version<br>tsc --version</pre><p>2. <strong>Test your setup:</strong></p><p>Create a simple src/main.ts:</p><pre>console.log(&quot;Hello, Web Workers!&quot;);</pre><p>Create index.html in the project root (not in src/):</p><pre>   &lt;!DOCTYPE html&gt;<br>   &lt;html lang=&quot;en&quot;&gt;<br>     &lt;head&gt;<br>       &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>       &lt;title&gt;Web Workers Tutorial&lt;/title&gt;<br>     &lt;/head&gt;<br>     &lt;body&gt;<br>       &lt;h1&gt;Web Workers Tutorial&lt;/h1&gt;<br>       &lt;script type=&quot;module&quot; src=&quot;./src/main.ts&quot;&gt;&lt;/script&gt;<br>     &lt;/body&gt;<br>   &lt;/html&gt;</pre><p>3. <strong>Start the dev server:</strong></p><pre> npm run dev</pre><p>The browser should open automatically. Check the console, you should see “Hello, Web Workers!”</p><p>4. <strong>Start Phase 1</strong>: <strong>The Problem</strong> — Demonstrate the blocking main thread problem</p><h4>Additional Resources</h4><p><strong>JavaScript:<br></strong><a href="http://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide">MDN JavaScript Guide — </a><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide</a><a href="http://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide"><br></a><a href="https://javascript.info/">JavaScript.info</a> — <a href="https://javascript.info/">javascript.info</a></p><p><strong>TypeScript:</strong><br>TypeScript Handbook — <a href="https://typescriptlang.org/docs">typescriptlang.org/docs</a><br>TypeScript Deep Dive — <a href="https://basarat.gitbook.io/typescript">basarat.gitbook.io/typescript</a></p><p>Web <strong>Workers</strong>:<br>MDN Web Workers API — <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API</a></p><p><strong>Build Tools:<br></strong>Vite Documentation — <a href="https://vitejs.dev/">vitejs.dev</a><br>TypeScript Compiler Options — <a href="https://typescriptlang.org/tsconfig">typescriptlang.org/tsconfig</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b8f86bc24a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Eliminated 500+ Lines of Form Boilerplate with React 19 and Zod]]></title>
            <link>https://medium.com/@muyiwamighty/how-i-eliminated-500-lines-of-form-boilerplate-with-react-19-and-zod-6fcd8706d2f0?source=rss-7a196e6b70bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fcd8706d2f0</guid>
            <category><![CDATA[react-19-features]]></category>
            <category><![CDATA[server-action]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react-forms]]></category>
            <dc:creator><![CDATA[Muyiwa Johnson]]></dc:creator>
            <pubDate>Wed, 24 Dec 2025 19:06:41 GMT</pubDate>
            <atom:updated>2025-12-25T11:02:08.337Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dkLx6WO3MZoccRLh9ti_rQ.png" /></figure><p>I’ve been building forms in React for years, and if there’s one thing that’s always frustrated me, it’s managing all those boolean states. You know the ones I’m talking about: isLoading, isSubmitting, isFetching, isError, isSuccess… the list goes on. Every form I built required me to manually track these states, synchronize them, and make sure they didn’t conflict with each other.</p><blockquote>Then React 19 introduced useActionState, and everything changed.</blockquote><p>In this post, I’ll show you how I’ve completely eliminated manual form state management in my Next.js applications by combining useActionState with <strong>Zod</strong> schemas and <strong>Server Actions</strong>. No more juggling multiple useStatehooks. No more race conditions. Just clean, type-safe forms that work.</p><h4>Table of contents</h4><p>∘ <a href="#472b">The Problem We’ve All Faced</a><br> ∘ <a href="#e395">The Solution: useActionState + Zod + Server Actions</a><br> ∘ <a href="#f926">How It Works: The Three-Part System</a><br> ∘ <a href="#7f19">The Benefits: Why This Approach Wins</a><br> ∘ <a href="#decd">Quick Tips</a><br> ∘ <a href="#2117">Quick Migration Guide</a><br> ∘ <a href="#0377">File Uploads</a><br> ∘ <a href="#620c">Conclusion</a></p><h4><strong>The Problem We’ve All Faced</strong></h4><p>Let me paint a picture that’s probably familiar. You’re building a login form, and you need to:</p><p>1. Show a loading spinner while the request is in flight</p><p>2. Display validation errors from the server</p><p>3. Handle success states</p><p>4. Prevent double submissions</p><p>5. Reset the form after success</p><p>Here’s what that typically looked like:</p><pre><br>function LoginForm() {<br>  const [isLoading, setIsLoading] = useState(false);<br>  const [isSubmitting, setIsSubmitting] = useState(false);<br>  const [errors, setErrors] = useState&lt;Record&lt;string, string[]&gt;&gt;({});<br>  const [isSuccess, setIsSuccess] = useState(false);<br>  const [error, setError] = useState&lt;string | null&gt;(null);<br><br>  const handleSubmit = async (e: React.FormEvent&lt;HTMLFormElement&gt;) =&gt; {<br>    e.preventDefault();<br>    setIsSubmitting(true);<br>    setIsLoading(true);<br>    setError(null);<br>    setErrors({});<br><br>    try {<br>      const formData = new FormData(e.currentTarget);<br>      const response = await fetch(&#39;/api/login&#39;, {<br>        method: &#39;POST&#39;,<br>        body: formData,<br>      });<br><br>      const data = await response.json();<br><br>      if (!response.ok) {<br>        setErrors(data.errors || {});<br>        setError(data.message || &#39;Login failed&#39;);<br>        return;<br>      }<br><br>      setIsSuccess(true);<br>      // Redirect or update UI<br>    } catch (err) {<br>      setError(&#39;An unexpected error occurred&#39;);<br>    } finally {<br>      setIsLoading(false);<br>      setIsSubmitting(false);<br>    }<br>  };<br><br>  return (<br>    &lt;form onSubmit={handleSubmit}&gt;<br>      {/* form fields */}<br>      &lt;button disabled={isSubmitting || isLoading}&gt;<br>        {isSubmitting ? &#39;Signing in...&#39; : &#39;Sign In&#39;}<br>      &lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>}</pre><p>Look at all that state management! And this is a <em>simple</em> form. Imagine what happens when you need to handle file uploads, conditional validation, or multi-step forms. The complexity <strong>explodes</strong>.</p><h4><strong>The Solution: useActionState + Zod + Server Actions</strong></h4><p>React 19’s useActionState hook (formerly useFormState) solves this by managing form state automatically. When combined with Zod for validation and Next.js Server Actions, you get a powerful, type-safe form handling system.</p><p>Here’s the same login form using the modern approach:</p><pre><br>&quot;use client&quot;;<br><br>import { useActionState } from &quot;react&quot;;<br>import { login } from &quot;@/actions/auth&quot;;<br><br>export function LoginForm() {<br>  const [response, formAction, isPending] = useActionState(login, null);<br><br>  return (<br>    &lt;form action={formAction}&gt;<br>      &lt;div&gt;<br>        &lt;label htmlFor=&quot;email&quot;&gt;Email&lt;/label&gt;<br>        &lt;input id=&quot;email&quot; name=&quot;email&quot; type=&quot;email&quot; required /&gt;<br>        {response?.errors?.email &amp;&amp; (<br>          &lt;p className=&quot;error&quot;&gt;{response.errors.email.join(&quot;, &quot;)}&lt;/p&gt;<br>        )}<br>      &lt;/div&gt;<br><br>      &lt;div&gt;<br>        &lt;label htmlFor=&quot;password&quot;&gt;Password&lt;/label&gt;<br>        &lt;input id=&quot;password&quot; name=&quot;password&quot; type=&quot;password&quot; required /&gt;<br>        {response?.errors?.password &amp;&amp; (<br>          &lt;p className=&quot;error&quot;&gt;{response.errors.password.join(&quot;, &quot;)}&lt;/p&gt;<br>        )}<br>      &lt;/div&gt;<br><br>      &lt;button type=&quot;submit&quot; disabled={isPending}&gt;<br>        {isPending ? &quot;Signing in...&quot; : &quot;Sign In&quot;}<br>      &lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>}</pre><p>That’s it. No useStatefor loading states. No manual error handling. The isPendingvalue is automatically managed by useActionState, and it updates whenever the form action is executing.</p><h4><strong>How It Works: The Three-Part System</strong></h4><p>The magic happens through three components working together:</p><p><strong>1. Zod Schema: Define Your Validation Rules</strong></p><p>First, define your validation schema with Zod:</p><pre>import { z } from &quot;zod&quot;;<br><br>export const login_schema = z.object({<br>  email: z.string().email({ message: &quot;Invalid email address.&quot; }),<br>  password: z.string().min(6, {<br>    message: &quot;Password must be at least 6 characters long.&quot;,<br>  }),<br>});<br><br>export type LoginDataType = z.infer&lt;typeof login_schema&gt;;</pre><p>This gives you:</p><ul><li>Type-safe validation</li><li>Clear error messages</li><li>TypeScript types automatically inferred</li></ul><p><strong>2. Server Action: Handle Form Submission</strong></p><p>Next, create a Server Action that uses your Zod schema:</p><pre>&quot;use server&quot;;<br><br>import { login_schema } from &quot;@/schemas/auth-schema&quot;;<br><br>interface LoginResult {<br>  errors?: Partial&lt;Record&lt;keyof LoginDataType, string[]&gt;&gt;;<br>  data?: {<br>    success: boolean;<br>    message: string;<br>  };<br>}<br><br>export async function login(<br>  prevState: unknown,<br>  formData: FormData<br>): Promise&lt;LoginResult&gt; {<br>  const rawData = Object.fromEntries(formData.entries());<br>  const validationResult = login_schema.safeParse(rawData);<br><br>  // If validation fails, return the errors<br>  if (!validationResult.success) {<br>    return {<br>      errors: validationResult.error.flatten().fieldErrors,<br>    };<br>  }<br><br>  // Process the login<br>  try {<br>    // Your authentication logic here<br>    const { error } = await supabase.auth.signInWithPassword({<br>      email: validationResult.data.email,<br>      password: validationResult.data.password,<br>    });<br><br>    if (error) {<br>      return {<br>        data: {<br>          success: false,<br>          message: error.message || &quot;Login failed&quot;,<br>        },<br>      };<br>    }<br><br>    // Success - redirect happens server-side<br>    redirect(&quot;/dashboard&quot;);<br>  } catch (error) {<br>    return {<br>      data: {<br>        success: false,<br>        message: &quot;An unexpected error occurred. Please try again.&quot;,<br>      },<br>    };<br>  }<br>}</pre><p>The key points:</p><ul><li>The action accepts prevState and formData</li><li>It validates with Zod using safeParse</li><li>It returns a structured response with errors and data</li><li>TypeScript ensures type safety throughout</li></ul><p><strong>3. useActionState: Connect Everything</strong></p><p>Finally, use useActionStatein your component:</p><pre>const [response, formAction, isPending] = useActionState(login, null);</pre><p>This gives you:</p><ul><li>response: The return value from your server action (contains errors and data)</li><li>formAction: The action function to pass to your form’s actionprop</li><li>action: Automatically managed boolean that’s truewhen the action is executing</li></ul><h4><strong>The Benefits: Why This Approach Wins</strong></h4><p>After using this pattern extensively, here’s what I’ve learned:</p><p><strong>1. Automatic State Management</strong></p><p>You never need to manually track isLoading, isSubmitting, or isFetching. The isPendingvalue from useActionStatehandles it all.</p><p><strong>2. Type Safety End-to-End</strong></p><p>Zod schemas give you validation rules and TypeScript types. Your server actions are type-safe, and your components get proper type inference.</p><p><strong>3. Server-Side Validation</strong></p><p>Validation happens on the server, which means:</p><ul><li>Better security (can’t be bypassed)</li><li>Consistent validation logic</li><li>No need to duplicate validation rules</li></ul><p><strong>4. Less Boilerplate</strong></p><p>Compare the code examples above. The traditional approach required 5+ `useState` hooks. The modern approach requires zero.</p><p><strong>5. Better Error Handling</strong></p><p>Errors are structured and type-safe. You get field-level errors automatically, and the response shape is consistent.</p><p><strong>6. Progressive Enhancement</strong></p><p>Forms work without JavaScript. If JS fails to load, the form still submits (though without the enhanced UX).</p><h4><strong>Quick Tips</strong></h4><p>Here are a few patterns I’ve found useful:</p><p><strong>Initial State</strong>: Define a consistent structure for your initial state:</p><pre><br>const initialState = { errors: {}, data: { success: false, message: &quot;&quot; } };</pre><p><strong>Success Messages</strong>: Use useEffectto show notifications:</p><pre>useEffect(() =&gt; {<br>  if (response?.data?.success) {<br>    toast.success(response.data.message);<br>  }<br>}, [response?.data]);</pre><p><strong>Disable During Submission</strong>: Use isPending to prevent double submissions:</p><pre>&lt;button disabled={isPending}&gt;{isPending ? &quot;Saving…&quot; : &quot;Save&quot;}&lt;/button&gt;</pre><h4><strong>Quick Migration Guide</strong></h4><p>To migrate existing forms:</p><p>1. <strong>Create a Zod schema</strong> for validation</p><p>2. <strong>Convert your handler</strong> to a Server Action (accepts prevStateand formData)</p><p>3. <strong>Replace </strong><strong>useState hooks</strong> with useActionState(serverAction, inititalState</p><p>4. <strong>Change </strong><strong>&lt;form onSubmit = {…}&gt;</strong> to <strong>&lt;form action={formAction}&gt;</strong></p><p>5. <strong>Update error display</strong> to use `response?.errors`</p><h4><strong>File Uploads</strong></h4><p>File uploads work seamlessly — just access files from `FormData` in your server action:</p><pre>export async function uploadDocument(prevState: unknown, formData: FormData) {<br>  const file = formData.get(&quot;document&quot;) as File | null;<br>  // Validate and process...<br>}</pre><h4><strong>Conclusion</strong></h4><p>React 19’s useActionState has fundamentally changed how I build forms. By combining it with Zod schemas and Server Actions, I’ve eliminated hundreds of lines of boilerplate code and made my forms more reliable, type-safe, and easier to maintain.</p><p>The best part? Once you understand the pattern, every form follows the same structure:</p><p>1. Define a Zod schema</p><p>2. Create a Server Action</p><p>3. Use `useActionState` in your component</p><p>No more juggling multiple state variables. No more race conditions. Just clean, working forms.</p><p>If you’re still managing form state manually, I encourage you to try this approach. Start with a simple form, and you’ll quickly see the benefits. Your future self (and your code reviewers) will thank you.</p><p><em>Have questions or want to share your own form handling patterns? Let me know in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fcd8706d2f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inversion of Control ?]]></title>
            <link>https://medium.com/@muyiwamighty/inversion-of-control-ae48369bb9e2?source=rss-7a196e6b70bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae48369bb9e2</guid>
            <category><![CDATA[frontend-engineering]]></category>
            <category><![CDATA[react-best-practices]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[code-maintainability]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Muyiwa Johnson]]></dc:creator>
            <pubDate>Wed, 03 Dec 2025 05:37:12 GMT</pubDate>
            <atom:updated>2025-12-03T05:37:12.939Z</atom:updated>
            <content:encoded><![CDATA[<h3>Inversion of Control ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L1DI8CjGWjRxhrE6U7Udig.png" /></figure><h4>Introduction</h4><p>If you have ever written a lot of code, you already know this truth:</p><p><strong>Sometimes, we give way too much control to our components.</strong></p><p>Not because we’re bad developers. Not because we don’t understand abstraction. But simply because, in an attempt to make things “reusable,” we accidentally create components that <em>seize</em> behavior instead of <em>hosting</em> it.</p><p>Most systems break not because the logic is wrong, but because <strong>the control is in the wrong place.</strong></p><p>Let’s look at a painfully familiar example.</p><pre>&lt;DataTable<br>  fetchUrl=&quot;/api/users&quot;<br>  enableSearch<br>  enableFiltering<br>  enableSorting<br>  enablePagination<br>  enableCSVExport<br>  filters={[...]}<br>  defaultSort=&quot;name&quot;<br>  onRowSelect={() =&gt; {}}<br>  onRowExpand={() =&gt; {}}<br>  pageSize={20}<br>  debounceMs={300}<br>  retryOnFail<br>  rowVariant=&quot;striped&quot;<br>  selectableRows<br>  expandableRows<br>  customCellRenderer={fn}<br>  errorRenderer={fn}<br>  emptyRenderer={fn}<br>  loadingRenderer={fn}<br>  // ...plus 20 more options<br>/&gt;</pre><p>You’ve seen this happen:</p><ul><li>functions that <strong>decide</strong> how to fetch</li><li>classes that <strong>create</strong> their own dependencies</li><li>components that <strong>choose</strong> API endpoints</li><li>utilities that <strong>hard-code</strong> logic</li><li>widgets that “think” they <strong>own</strong> the business rules</li></ul><p>Every time a module takes ownership of behavior that should be supplied from outside, it grows tighter, heavier, and harder to reuse.</p><p>The above example is not a <strong>DataTable </strong>problem, it is a <strong>control problem. </strong>This is where <strong><em>Inversion of control (IoC) </em></strong>comes to shine.</p><h4>what is inversion of control</h4><p>Inversion of Control (IoC) is not a pattern.<br>It’s not a library.<br>It’s not a framework trick.</p><p>It is a design philosophy:</p><blockquote><strong>The provider controls the lifecycle; the consumer controls the behavior.</strong></blockquote><p>Instead of components <em>deciding the rules</em>, they <em>host</em> the rules supplied by their parent. lets think of it this way</p><h4>Without IoC</h4><p>The DataTable decides:</p><ul><li><strong>how</strong> to fetch</li><li><strong>how</strong> to sort</li><li><strong>how</strong> to filter</li><li><strong>how</strong> to transform rows</li><li><strong>how</strong> to debounce</li><li><strong>how</strong> to paginate</li><li><strong>when</strong> to run all these</li></ul><p>It owns the entire flow.</p><pre>Parent ----&gt; DataTable ----&gt; fetch<br>                          ----&gt; sort<br>                          ----&gt; filter<br>                          ----&gt; debounce<br>                          ----&gt; pagination<br>                          ----&gt; render logic<br>                          ----&gt; error logic<br>                          ----&gt; row transformation<br>                          ----&gt; everything else ....</pre><p>The component owns ALL the logic. see example below</p><pre>// BLOATED DATATABLE (TOO MUCH CONTROL)<br><br><br>export function DataTable(props) {<br>  const {<br>    fetchUrl,<br>    enableSearch,<br>    enableFiltering,<br>    enableSorting,<br>    enablePagination,<br>    filters,<br>    defaultSort,<br>    pageSize,<br>    debounceMs,<br>    customCellRenderer,<br>    errorRenderer,<br>    emptyRenderer,<br>    loadingRenderer,<br>  } = props;<br><br>  const [rows, setRows] = useState([]);<br>  const [search, setSearch] = useState(&quot;&quot;);<br>  const [sort, setSort] = useState(defaultSort);<br>  const [page, setPage] = useState(1);<br><br>  // It fetches by itself<br>  useEffect(() =&gt; {<br>    fetch(fetchUrl)<br>      .then(r =&gt; r.json())<br>      .then(data =&gt; {<br>        let result = data;<br><br>        // It sorts by itself<br>        if (enableSorting) {<br>          result = sortRows(result, sort);<br>        }<br><br>        // It filters by itself<br>        if (enableFiltering) {<br>          result = filterRows(result, filters);<br>        }<br><br>        // It searches by itself<br>        if (enableSearch) {<br>          result = searchRows(result, search);<br>        }<br><br>        // It paginates by itself<br>        if (enablePagination) {<br>          result = paginate(result, page, pageSize);<br>        }<br><br>        setRows(result);<br>      });<br>  }, [fetchUrl, search, sort, page, filters]);<br><br>  return (<br>    &lt;table&gt;<br>      {/* ... */}<br>    &lt;/table&gt;<br>  );<br>}</pre><h4>With IoC</h4><p>The DataTable decides only:</p><ul><li>when sorting should trigger</li><li>when filtering should trigger</li><li>when pagination should advance</li><li>when rows should be rendered</li></ul><p>But the user injects the behaviors:</p><ul><li>fetch logic</li><li>sorting logic</li><li>filtering logic</li><li>transformation logic</li><li>cell rendering logic</li></ul><blockquote>The behavior is injected. The lifecycle is controlled.</blockquote><pre>Parent ---- injects behaviors ----&gt; fetch()<br>                                    sort()<br>                                    filter()<br>                                    render()<br><br>DataTable ---- controls ----&gt; lifecycle<br>                              when sorting triggers<br>                              when filtering triggers<br>                              when pagination happens<br>                              when rows re-render</pre><p>Behavior flows <strong>downward</strong> from the parent. <br>Lifecycle flows <strong>upward</strong> from the component.</p><p>Let’s rewrite the DataTable using IoC principles. We remove all behavior from the table. We keep only lifecycle + rendering.</p><pre>// IOC TABLE (LEAN, FLEXIBLE, BEAUTIFUL)<br><br><br>type TableProps&lt;T&gt; = {<br>  rows: T[];<br>  sort: SortState;<br>  onSortChange: (s: SortState) =&gt; void;<br>  filters: FilterState;<br>  onFilterChange: (f: FilterState) =&gt; void;<br>  children: React.ReactNode;<br>};<br><br>export function Table&lt;T&gt;({<br>  rows,<br>  sort,<br>  onSortChange,<br>  filters,<br>  onFilterChange,<br>  children,<br>}: TableProps&lt;T&gt;) {<br>  return (<br>    &lt;&gt;<br>      {/* Sorting UI owned by table */}<br>      &lt;SortControls value={sort} onChange={onSortChange} /&gt;<br><br>      {/* Filter UI owned by table */}<br>      &lt;FilterControls value={filters} onChange={onFilterChange} /&gt;<br><br>      &lt;table&gt;<br>        {children}<br>        &lt;tbody&gt;<br>          {rows.map((r, i) =&gt; (<br>            &lt;tr key={i}&gt;{/* table only renders */}&lt;/tr&gt;<br>          ))}<br>        &lt;/tbody&gt;<br>      &lt;/table&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>The table no longer: fetches, filters, sorts, paginates, transforms, searches, debounces.</p><p>It simply orchestrates the lifecycle:</p><ul><li>“Sorting changed — parent, do something.”</li><li>“Filtering changed — parent, do something.”</li><li>“Render these rows.”</li></ul><p>Everything else lives in the parent.</p><h4>Parent Now Controls Behavior</h4><pre>function UsersPage() {<br>  const [sort, setSort] = useState({ column: &quot;name&quot;, direction: &quot;asc&quot; });<br>  const [filters, setFilters] = useState({ status: &quot;active&quot; });<br><br>  const rows = useUserQuery({ sort, filters }); // ← consumer decides behavior<br><br>  return (<br>    &lt;Table<br>      rows={rows}<br>      sort={sort}<br>      onSortChange={setSort}<br>      filters={filters}<br>      onFilterChange={setFilters}<br>    &gt;<br>      &lt;Table.Column title=&quot;Name&quot; render={(user) =&gt; user.name} /&gt;<br>      &lt;Table.Column title=&quot;Email&quot; render={(user) =&gt; user.email} /&gt;<br>    &lt;/Table&gt;<br>  );<br>}</pre><p>Now the table doesn’t care if rows come from:</p><ul><li>REST</li><li>GraphQL</li><li>tRPC</li><li>localStorage</li><li>IndexedDB</li><li>mock data</li><li>a cache</li><li>server components</li><li>a streaming API</li></ul><p><strong>The behavior is injected. The lifecycle is owned.</strong></p><p>This is <strong>Inversion of Control</strong>.</p><h3>Conclusion</h3><p>At the end of the day, this was never about building the “perfect” DataTable. It was about <strong>control </strong>and why giving components too much of it always backfires.</p><p>Once I started using Inversion of Control, my components instantly became lighter, easier to reuse, and way less stressful to maintain. The magic is simple:</p><blockquote><strong><em>Let the component handle </em>when<em>, and let you decide </em>how<em>.</em></strong></blockquote><p>That’s the shift.Stop letting components own your logic. Start letting them <em>host</em> it. Your future self and your entire codebase will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae48369bb9e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Secure Code Sandbox: What I learned about iframe isolation and postMessage]]></title>
            <link>https://medium.com/@muyiwamighty/building-a-secure-code-sandbox-what-i-learned-about-iframe-isolation-and-postmessage-a6e1c45966df?source=rss-7a196e6b70bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6e1c45966df</guid>
            <category><![CDATA[isolation]]></category>
            <category><![CDATA[codesandbox]]></category>
            <category><![CDATA[iframe-embed]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Muyiwa Johnson]]></dc:creator>
            <pubDate>Mon, 24 Nov 2025 18:00:22 GMT</pubDate>
            <atom:updated>2025-11-24T18:00:22.067Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LvHyO8D9W4AbwJo82gXKtg.png" /></figure><p>I’ve always wondered how CodePen and JSFiddle work. You type code, and boom, it just runs. Magic, right?</p><p>Well, I decided to find out. And turns out, the answer is iframes. Those things I’ve been avoiding for years because they seemed… old? Boring? I don’t know, I just never gave them much thought.</p><p>But here’s the thing , iframes are actually pretty cool. And building a code playground is the perfect way to learn why.</p><h4>The Question That Started It All</h4><p>How do you let someone write HTML, CSS, and JavaScript, and see it run in real-time? Without breaking your app? Without security issues?</p><p>The answer: iframes. Specifically, sandboxed iframes with srcdoc</p><h4>What I Built</h4><p>I built a web playground, basically a <strong>mini CodePen</strong>. You can write HTML, CSS, and JavaScript, see a live preview, and even see console output. It has dark mode, code formatting, and all that good stuff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i9SftKf1LAWsQ_WQmwyhug.png" /></figure><h3>Part 1: Understanding Iframes (The Basics)</h3><p>Iframes are basically <strong>windows</strong> inside your webpage. They show another webpage. Simple concept, but powerful.</p><p>When someone writes code in your playground, you need to:</p><p>1. Run their code safely (can’t break your app)</p><p>2. Isolate it completely (their CSS shouldn’t mess up your UI)</p><p>3. Execute JavaScript (but safely)</p><p>Iframes do all of this. They create a completely separate environment. It’s like giving someone their own little browser window inside your page.</p><h4>The Magic: srcdoc vs src</h4><p>Here’s where it gets interesting. You can load an iframe two ways:</p><pre>// Old way - load from a URL<br>iframe.src = &quot;https://example.com&quot;;</pre><pre>// New way - inject HTML directly<br>iframe.srcdoc = &quot;&lt;html&gt;...&lt;/html&gt;&quot;;</pre><p>For a playground, you want srcdoc. Why? Because you’re generating the HTML on the fly. The user types code, you combine it into a full HTML document, and inject it directly.</p><p>No server needed. No file uploads. Just pure JavaScript magic.</p><h4>Sandboxing = Security</h4><p>But wait, if you’re running user code, isn’t that dangerous? Yes. That’s why sandboxing exists.</p><pre>&lt;iframe sandbox=&quot;allow-scripts allow-same-origin&quot;&gt;&lt;/iframe&gt;</pre><p>This tells the browser: “Hey, let JavaScript run, but don’t let it access the parent window. Keep it isolated.”</p><p>The allow-same-originpart is important , it lets the iframe communicate with the parent (we’ll need that for console output).</p><h3>Part 2: Building the Preview</h3><p>So here’s how it works. User types code in three editors (HTML, CSS, JS). I need to combine them into one document and show it in the iframe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9m3EqZR1Oe0VLCtHnUhYhA.png" /></figure><h4>Generating the Preview HTML</h4><p>Inside the PreviewPane component, I use a `useCallback` to generate the HTML document. It takes the three code strings and builds a complete HTML document, including the console interceptor:</p><pre>const generatePreviewHTML = useCallback((): string =&gt; {<br>  return `<br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot;&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>  &lt;style&gt;<br>    * { <br>      margin: 0; <br>      padding: 0; <br>      box-sizing: border-box; <br>    }<br>    ${css}<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  ${html}<br>  &lt;script&gt;<br>    ${getConsoleInterceptorScript()}<br>    <br>    try {<br>      ${js}<br>    } catch (error) {<br>      if (window.sendConsoleMessage) {<br>        window.sendConsoleMessage(&#39;error&#39;, [error.message]);<br>      }<br>    }<br>  &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;`.trim();<br>}, [html, css, js]);</pre><p>Then I inject it into the iframe:</p><pre>useEffect(() =&gt; {<br>  const iframe = iframeRef.current;<br>  if (!iframe) return;<br>  <br>  iframe.srcdoc = generatePreviewHTML();<br>}, [generatePreviewHTML]);</pre><p>The usecallback memoizes the function so it only regenerates when html, css, or js changes. Then the useEffect updates the iframe whenever the generated HTML changes.</p><p>That’s it. The iframe renders it. The user’s code runs. Magic.</p><h4>Real-Time Updates</h4><p>But we want it to update as the user types, right? Well, not on every keystroke, that would be too slow. I used <strong>debouncing</strong> in the App component. The useDebounce hook waits 300ms after the user stops typing, then updates the value:</p><pre>// In App.tsx<br>const debouncedHtml = useDebounce(html, 300);<br>const debouncedCss = useDebounce(css, 300);<br>const debouncedJs = useDebounce(js, 300);</pre><pre>// Pass debounced values to PreviewPane<br>&lt;PreviewPane<br>  html={debouncedHtml}<br>  css={debouncedCss}<br>  js={debouncedJs}<br>  onConsoleMessage={handleConsoleMessage}<br>/&gt;</pre><p>The PreviewPane receives the debounced values, so it only regenerates the HTML 300ms after typing stops. The usecallBack in PreviewPane ensures the HTML generation function only recreates when the values actually change.</p><p>Smooth updates without lag. Perfect.</p><h4>Part 3: The Console Problem (And Solution)</h4><p>Here’s where it got tricky. The user writes console.log(“hello”) in their JavaScript. Where does that output go?</p><p>Into the iframe’s console. Which we can’t see. Because it’s <a href="https://developer.mozilla.org/en-US/docs/Glossary/Browsing_context"><strong>isolated</strong></a>.</p><h4>The Solution: postMessage</h4><p>This is where postMessage comes in. It’s the safe way for iframes to talk to their parent window.</p><p>Here’s what I did:</p><p>1. Inside the iframe, I intercept all console methods</p><p>2. When someone calls console.log(), I send a message to the parent</p><p>3. The parent receives it and displays it in the console panel</p><p>Here’s how the architecture works:</p><pre>+------------------------+<br>| Parent React App       |<br>| - Editor Panels        |<br>| - Console Panel        |<br>| - Message Listener     |<br>+------------+-----------+<br>             |<br>             | postMessage<br>             v<br>+--------------------------+<br>| Sandboxed Iframe         |<br>| - User HTML/CSS/JS       |<br>| - Hijacked console.log   |<br>| - Error listener         |<br>+--------------------------+</pre><p>The console interceptor is a separate function that gets injected into the iframe:</p><pre>const getConsoleInterceptorScript = (): string =&gt; {<br>  return `<br>(function() {<br>  // Store original console methods<br>  const original = {<br>    log: console.log,<br>    error: console.error,<br>    warn: console.warn,<br>    info: console.info<br>  };</pre><pre>// Send console message to parent window (expose globally)<br>  window.sendConsoleMessage = function(type, args) {<br>    window.parent.postMessage({<br>      type: &#39;console&#39;,<br>      log: {<br>        type: type,<br>        args: args.map(arg =&gt; {<br>          if (typeof arg === &#39;object&#39;) {<br>            try {<br>              return JSON.stringify(arg, null, 2);<br>            } catch {<br>              return String(arg);<br>            }<br>          }<br>          return String(arg);<br>        })<br>      }<br>    }, &#39;*&#39;);<br>  };</pre><pre>// Override console methods<br>  [&#39;log&#39;, &#39;error&#39;, &#39;warn&#39;, &#39;info&#39;].forEach(method =&gt; {<br>    console[method] = function(...args) {<br>      original[method](...args);<br>      window.sendConsoleMessage(method, args);<br>    };<br>  });</pre><pre>// Catch runtime errors<br>  window.addEventListener(&#39;error&#39;, (e) =&gt; {<br>    window.sendConsoleMessage(&#39;error&#39;, [<br>      \`Error: \${e.message}\`,<br>      \`File: \${e.filename}\`,<br>      \`Line: \${e.lineno}\`<br>    ]);<br>  });</pre><pre>// Catch unhandled promise rejections<br>  window.addEventListener(&#39;unhandledrejection&#39;, (e) =&gt; {<br>    window.sendConsoleMessage(&#39;error&#39;, [\`Unhandled Promise Rejection: \${e.reason}\`]);<br>  });<br>})();<br>  `.trim();<br>};</pre><p>This script gets injected into the iframe’s HTML. Then in the parent window, I listen for messages:</p><pre>useEffect(() =&gt; {<br>  const handleMessage = (event: MessageEvent) =&gt; {<br>    if (event.data.type === &quot;console&quot; &amp;&amp; event.data.log) {<br>      onConsoleMessage(event.data.log);<br>    }<br>  };</pre><pre>window.addEventListener(&quot;message&quot;, handleMessage);<br>  return () =&gt; window.removeEventListener(&quot;message&quot;, handleMessage);<br>}, [onConsoleMessage]);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Vt9eyF9rPglMOqP_aZhUA.png" /></figure><p>It works! Console logs, errors, warnings, all captured and displayed. Even runtime errors are caught.</p><h3>Part 4: The Tech Stack</h3><p>I used:</p><p><strong>React + TypeScript</strong> — Because type safety is nice</p><p><strong>CodeMirror 6 </strong>— For the code editor with syntax highlighting</p><p><strong>Prettier</strong> — For code formatting (one-click format button)</p><p><strong>Tailwind CSS</strong> — For styling (because I’m lazy)</p><p><strong>Radix UI</strong> — For accessible components</p><p>Nothing too fancy. Just solid tools that work well together.</p><h3>Part 5: Challenges I Faced</h3><h4>Challenge 1: Console Output</h4><p>The hardest part was figuring out how to get console output. I spent way too long trying different approaches before discovering postMessage.</p><p>The key insight: you can’t access the iframe’s console directly. You have to intercept it from inside the iframe and send messages out.</p><h4>Challenge 2: Error Handling</h4><p>JavaScript errors in the iframe need to be caught and displayed. I added error event listeners:</p><pre>window.addEventListener(&quot;error&quot;, (e) =&gt; {<br>  window.parent.postMessage(<br>    {<br>      type: &quot;console&quot;,<br>      log: {<br>        type: &quot;error&quot;,<br>        args: [`Error: ${e.message}`, `Line: ${e.lineno}`],<br>      },<br>    },<br>    &quot;*&quot;,<br>  );<br>});</pre><p>Now errors show up in the console panel too. Nice.</p><p>I used to think iframes were outdated. Turns out they’re perfect for:</p><h4>Iframes Are Actually Powerful</h4><p>I used to think iframes were outdated. Turns out they’re perfect for:</p><ul><li>Sandboxing user code</li><li>Creating isolated environments</li><li>Security (when used correctly)</li></ul><h4>postMessage Is Your Friend</h4><p>Before this project, I’d never used postMessage. Now I see it everywhere. It’s the standard way for frames to communicate safely.</p><h4>I am done?</h4><p>If you’re curious about how CodePen or JSFiddle work, try building your own. It’s a great learning project. And you’ll finally understand iframes.</p><p><strong>Try it out!</strong></p><p><a href="https://test-web-playground.netlify.app/">Live demo</a></p><p><a href="https://github.com/MuyiwaJohnson/html-css-js-playground">GitHub Repository</a></p><p>Feel free to fork it, break it, learn from it.</p><p><strong>TL;DR</strong>: Iframes + postMessage + debouncing = a working code playground. Who knew?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6e1c45966df" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>