<?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 Rupanjan Hari on Medium]]></title>
        <description><![CDATA[Stories by Rupanjan Hari on Medium]]></description>
        <link>https://medium.com/@hrupanjan?source=rss-5309245d5187------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*yiQGoJ6KW3pTjxOf</url>
            <title>Stories by Rupanjan Hari on Medium</title>
            <link>https://medium.com/@hrupanjan?source=rss-5309245d5187------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:20:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hrupanjan/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[How We Cut Development Time by 60% Using Mock Service Worker + Faker.js]]></title>
            <link>https://medium.com/@hrupanjan/how-we-cut-development-time-by-60-using-mock-service-worker-faker-js-1e867b2498dc?source=rss-5309245d5187------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e867b2498dc</guid>
            <category><![CDATA[dx-pattern]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[msw]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Rupanjan Hari]]></dc:creator>
            <pubDate>Sat, 07 Feb 2026 08:17:05 GMT</pubDate>
            <atom:updated>2026-02-23T11:05:15.729Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Decoupling Frontend and Backend Development with MSW Accelerates Your Workflow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5iFfKkV_85ECZH6bwV8c-g.png" /></figure><p>In modern web development, frontend and backend teams often work in parallel. However, this parallelism can introduce bottlenecks when the frontend depends on backend APIs that are still under development. <strong>Mock Service Worker (MSW)</strong> provides an elegant solution by intercepting network requests and mocking API responses, enabling true frontend-backend decoupling.</p><h3>The Problem: Dependency Bottlenecks</h3><p>Traditional development workflows face several challenges:</p><ul><li>Frontend developers wait for backend APIs to be ready</li><li>Backend changes can break frontend development</li><li>Testing requires a running backend server</li><li>Development environments are difficult to set up</li><li>Realistic test data is hard to maintain</li></ul><h3>The MSW Solution: A Three-Layer Architecture</h3><p>A robust MSW implementation consists of three key layers:</p><h4>1. Fake Data Store with Faker.js</h4><p>Instead of hardcoding mock data, use <strong>Faker.js</strong> to generate realistic, dynamic datasets:</p><pre>import { faker } from &#39;@faker-js/faker&#39;;<br><br>export const generateUser = () =&gt; ({<br>  id: faker.string.uuid(),<br>  name: faker.person.fullName(),<br>  email: faker.internet.email(),<br>  avatar: faker.image.avatar(),<br>  role: faker.helpers.arrayElement([&#39;admin&#39;, &#39;user&#39;, &#39;moderator&#39;]),<br>  createdAt: faker.date.past().toISOString(),<br>});<br><br>export const users = Array.from({ length: 50 }, generateUser);</pre><p><strong>Benefits:</strong></p><ul><li><strong>Variety</strong>: Every page refresh generates different data</li><li><strong>Realism</strong>: Data looks like production</li><li><strong>Volume</strong>: Easily generate hundreds of records for pagination testing</li><li><strong>Consistency</strong>: Centralized data generation logic</li></ul><h4>2. Domain-Specific Handlers</h4><p>Organize handlers by feature domain, consuming data from the fake store:</p><pre>import { http, HttpResponse } from &#39;msw&#39;;<br>import { users, generateUser } from &#39;../fake-store/users&#39;;<br><br>export const handlers = [<br>  http.get(&#39;/api/users&#39;, ({ request }) =&gt; {<br>    const url = new URL(request.url);<br>    const page = parseInt(url.searchParams.get(&#39;page&#39;) || &#39;1&#39;);<br>    const pageSize = parseInt(url.searchParams.get(&#39;pageSize&#39;) || &#39;10&#39;);<br>    <br>    const start = (page - 1) * pageSize;<br>    const paginatedUsers = users.slice(start, start + pageSize);<br>    <br>    return HttpResponse.json({<br>      data: paginatedUsers,<br>      total: users.length,<br>      page,<br>      pageSize,<br>    });<br>  }),<br>  <br>  http.post(&#39;/api/users&#39;, async ({ request }) =&gt; {<br>    const newUser = await request.json();<br>    const user = { ...generateUser(), ...newUser };<br>    users.push(user);<br>    return HttpResponse.json(user, { status: 201 });<br>  }),<br>];</pre><h4>3. Centralized Server Setup</h4><p>Compose all handlers into a single mock server:</p><pre>import { setupServer } from &quot;msw/node&quot;;<br>import { handlers as authHandlers } from &quot;./authHandlers&quot;;<br>import { handlers as userHandlers } from &quot;./userHandlers&quot;;<br><br>export const server = setupServer(<br>    ...authHandlers,<br>    ...userHandlers,<br>);</pre><h3>Real-World Workflow Benefits</h3><h4>Scenario 1: Building a Data Table Component</h4><p>Your task: Build a user management table with pagination, sorting, and filtering.</p><p><strong>Without MSW:</strong></p><ul><li>Wait for backend pagination API</li><li>Manual testing requires database setup</li><li>Backend downtime blocks frontend progress</li></ul><p><strong>With MSW + Faker:</strong></p><pre>// Generate 1000 users instantly<br>export const users = Array.from({ length: 1000 }, generateUser);</pre><ul><li>Test edge cases (empty states, large datasets, special characters)</li><li>Implement sorting/filtering logic independently</li><li>Validate UI responsiveness with realistic data volumes</li></ul><h4>Scenario 2: Form Validation Testing</h4><p>Test form validation with diverse data patterns:</p><pre>export const generateInvalidUser = () =&gt; ({<br>  email: faker.internet.email().replace(&#39;@&#39;, &#39;&#39;), // Invalid email<br>  name: faker.string.alpha({ length: 1 }), // Too short<br>  age: faker.number.int({ min: 150, max: 200 }), // Invalid age<br>});</pre><h4>Scenario 3: Stateful Interactions</h4><p>MSW handlers can maintain state, simulating real backend behavior:</p><pre>let sessionUsers = [...users];<br><br>http.delete(&#39;/api/users/:id&#39;, ({ params }) =&gt; {<br>  sessionUsers = sessionUsers.filter(u =&gt; u.id !== params.id);<br>  return HttpResponse.json({ success: true });<br>}),</pre><h3>Advanced Patterns</h3><h4>Seeded Data for Reproducible Tests</h4><pre>import { faker } from &#39;@faker-js/faker&#39;;<br><br>faker.seed(12345); // Same data every time<br>export const testUsers = Array.from({ length: 10 }, generateUser);</pre><h4>Response Delays for Loading States</h4><pre>http.get(&#39;/api/users&#39;, async () =&gt; {<br>  await delay(1500); // Test loading spinners<br>  return HttpResponse.json(users);<br>}),</pre><h4>Error Scenarios</h4><pre>http.get(&#39;/api/users/:id&#39;, ({ params }) =&gt; {<br>  const user = users.find(u =&gt; u.id === params.id);<br>  if (!user) {<br>    return HttpResponse.json(<br>      { error: &#39;User not found&#39; },<br>      { status: 404 }<br>    );<br>  }<br>  return HttpResponse.json(user);<br>}),</pre><h3>Implementation Best Practices</h3><ol><li><strong>Separate Data from Handlers</strong>: Keep fake stores independent</li><li><strong>Use TypeScript Interfaces</strong>: Define contracts between frontend and backend</li><li><strong>Generate Realistic Data</strong>: Use Faker’s domain-specific methods</li><li><strong>Control Randomness</strong>: Seed Faker for deterministic tests</li><li><strong>Mirror Production Structure</strong>: Match real API response shapes</li><li><strong>Version Your Mocks</strong>: Update mocks alongside API documentation</li></ol><h3>The Complete Development Loop</h3><ol><li>Product defines feature requirements</li><li>Backend designs API contract</li><li>Frontend creates TypeScript interfaces</li><li>Frontend builds fake store with Faker</li><li>Frontend implements MSW handlers</li><li>Frontend develops UI components ← Independent progress</li><li>Backend implements real API ← Independent progress</li><li>Integration testing verifies contract</li><li>Deploy</li></ol><blockquote>Even agents love this development cycle. Features become much more ready for production deployments. Agents like Claude Code or Github Copilot can follow this cycle with custom skills.</blockquote><h3>Measuring Success</h3><p><strong>Before MSW + Faker:</strong></p><ul><li>Setup time: 2+ hours (database, backend server)</li><li>Blocked days: 3–5 waiting for APIs</li><li>Test flakiness: High (network/database issues)</li></ul><p><strong>After MSW + Faker:</strong></p><ul><li>Setup time: 5 minutes (npm install, npm run dev)</li><li>Blocked days: 0</li><li>Test flakiness: Minimal (deterministic responses)</li></ul><h3>Conclusion</h3><p>The combination of <strong>MSW</strong> and <strong>Faker.js</strong> transforms frontend development from a dependent process to an autonomous workflow. By creating a realistic, stateful mock backend, teams can:</p><ul><li>Develop features in parallel with backend teams</li><li>Test edge cases without complex setup</li><li>Onboard developers in minutes</li><li>Build confidence in API contracts</li><li>Ship features faster</li></ul><p>The three-layer architecture (fake store → handlers → server) provides maintainability, while Faker ensures your development environment mirrors production reality. The result? A development experience that’s faster, more reliable, and genuinely enjoyable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e867b2498dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Supercharge Your React App: Offload Heavy Tasks to Web Workers with Comlink]]></title>
            <link>https://medium.com/@hrupanjan/supercharge-your-react-app-offload-heavy-tasks-to-web-workers-with-comlink-97b4b210450b?source=rss-5309245d5187------2</link>
            <guid isPermaLink="false">https://medium.com/p/97b4b210450b</guid>
            <category><![CDATA[webworker]]></category>
            <category><![CDATA[background-processing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Rupanjan Hari]]></dc:creator>
            <pubDate>Fri, 05 Sep 2025 08:45:26 GMT</pubDate>
            <atom:updated>2025-09-05T08:45:26.114Z</atom:updated>
            <content:encoded><![CDATA[<h4>Keep your UI buttery smooth while processing data in the background — A complete guide to implementing Web Workers with Comlink in a React + Vite application</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQAsiKn4AN9L7RKgVsiC1Q.png" /></figure><p>Ever had your React app freeze up when processing large datasets or performing complex calculations? You’re not alone. JavaScript’s single-threaded nature means that CPU-intensive tasks can block the main thread, making your UI unresponsive and frustrating your users.</p><blockquote>Enter <strong>Web Workers</strong> and <strong>Comlink</strong> — a powerful combination that lets you offload heavy computation to background threads while keeping your UI silky smooth. In this post, we’ll explore how to set up and use Web Workers with <a href="https://www.npmjs.com/package/comlink">Comlink</a> in a modern React application.</blockquote><h3>What Are Web Workers?</h3><p>Web Workers allow you to run JavaScript code in the background, separate from the main UI thread. This means you can:</p><ul><li>Process large datasets without blocking the UI</li><li>Perform complex calculations in parallel</li><li>Handle API responses and data transformation asynchronously</li><li>Keep your app responsive even during intensive operations</li></ul><h3>Why Comlink?</h3><p>While Web Workers are powerful, the traditional way of communicating with them (using postMessage and event listeners) can be cumbersome. <strong>Comlink</strong> simplifies this by providing a seamless RPC (Remote Procedure Call) interface, making worker communication feel like regular function calls.</p><h3>Setting Up the Foundation</h3><h4>1. Install Dependencies</h4><p>First, let’s install the necessary packages:</p><pre>npm install comlink<br>npm install -D vite-plugin-comlink</pre><h4>2. Configure Vite</h4><p>Update your vite.config.ts to include Comlink support:</p><pre>import path from &quot;path&quot;;<br>import react from &quot;@vitejs/plugin-react-swc&quot;;<br>import { defineConfig } from &quot;vite&quot;;<br>import { comlink } from &quot;vite-plugin-comlink&quot;;<br><br>export default defineConfig({<br>    plugins: [<br>        react(),<br>        comlink(), // Add Comlink plugin<br>        // ...other plugins<br>    ],<br>    worker: {<br>        plugins: [comlink()], // Enable Comlink for workers<br>    },<br>    resolve: {<br>        alias: {<br>            &quot;@&quot;: path.resolve(__dirname, &quot;./src&quot;),<br>        },<br>    },<br>});</pre><h4>3. Type Definitions</h4><p>Add Comlink types to your vite-env.d.ts:</p><pre>/// &lt;reference types=&quot;vite/client&quot; /&gt;<br>/// &lt;reference types=&quot;vite-plugin-comlink/client&quot; /&gt;</pre><h3>Creating Your First Worker</h3><p>Let’s create a practical example — a data processing worker that handles role data transformation:</p><h4>1. The Worker Implementation</h4><pre>// @/workers/remote-logger/worker.ts<br><br>import * as seq from &quot;seq-logging&quot;;<br>import { config } from &quot;@/utils/app-config&quot;;<br>import { RemoteLogLevel } from &quot;../../models/remote-log-level&quot;;<br><br>const logger = new seq.Logger({<br>    serverUrl: config.env.LOG_URL,<br>    apiKey: config.env.LOG_API_KEY,<br>    onError: (evt) =&gt; {<br>        console.error(evt?.message);<br>    },<br>});<br><br>type Properties = Record&lt;string, string | number | boolean | undefined | null&gt;;<br><br>const getLevelString = (severity: RemoteLogLevel) =&gt; {<br>    switch (severity) {<br>        case RemoteLogLevel.Debug:<br>            return &quot;Debug&quot;;<br>        case RemoteLogLevel.Info:<br>            return &quot;Information&quot;;<br>        case RemoteLogLevel.Error:<br>            return &quot;Error&quot;;<br>        case RemoteLogLevel.Warn:<br>            return &quot;Warning&quot;;<br>        case RemoteLogLevel.Fatal:<br>            return &quot;Fatal&quot;;<br>        default:<br>            return &quot;Verbose&quot;;<br>    }<br>};<br><br>export const logRemoteServerMessage = (<br>    message: string,<br>    properties?: Properties,<br>    exception?: string,<br>    severity: RemoteLogLevel = RemoteLogLevel.Info<br>) =&gt; {<br>    try {<br>        const now = new Date();<br>        const dataLog = {<br>            messageTemplate: message,<br>            level: getLevelString(severity),<br>            timestamp: now,<br>            properties,<br>            exception,<br>        };<br>        <br>        if (typeof message === &quot;string&quot; &amp;&amp; dataLog) {<br>            logger.emit(dataLog);<br>        }<br>    } catch (error) {<br>        console.log(`Error occurred while logging! Error: ${error}`);<br>    }<br>};<br><br>export const logErrorMessage = (<br>    message: string,<br>    properties?: Properties,<br>    exception?: string<br>) =&gt; {<br>    logRemoteServerMessage(<br>        message,<br>        properties,<br>        exception,<br>        RemoteLogLevel.Error<br>    );<br>};<br><br>export const close = () =&gt; {<br>    logger.close();<br>};</pre><h4>2. Setting Up the Worker Registry</h4><p>Create a centralized index file to manage all your workers:</p><pre>// @/workers/index.ts<br>/* eslint-disable no-undef */<br><br>const remoteLogger = new ComlinkWorker&lt;typeof import(&quot;./remote-logger/worker&quot;)&gt;(<br>    new URL(&quot;./remote-logger/worker&quot;, import.meta.url)<br>);<br><br>export { remoteLogger };</pre><h4>3. Using Workers in Your React Components</h4><p>Now comes the fun part — using these workers in your React components or util functions:</p><pre>import { remoteLogger } from &quot;@/workers&quot;;<br><br>export const logError = async (<br>    message: string,<br>    properties?: Record&lt;string, any&gt;,<br>    exception?: string<br>) =&gt; {<br>    // This logging happens in a Web Worker<br>    await remoteLogger.logErrorMessage(message, properties, exception);<br>};<br><br>export const logInfo = async (<br>    message: string,<br>    properties?: Record&lt;string, any&gt;<br>) =&gt; {<br>    await remoteLogger.logRemoteServerMessage(message, properties);<br>};</pre><h3>When to Use Web Workers</h3><p>Web Workers are perfect for:</p><ul><li>✅ Data processing and transformation</li><li>✅ Image/video processing</li><li>✅ Complex calculations</li><li>✅ API response parsing</li><li>✅ Background logging</li><li>✅ Cryptographic operations</li></ul><p>Avoid for:</p><ul><li>❌ Simple operations</li><li>❌ DOM manipulation</li><li>❌ Operations that need immediate results</li><li>❌ Small datasets</li></ul><h3>Conclusion</h3><p>Web Workers with Comlink provide a powerful way to keep your React applications responsive while handling intensive tasks. By offloading heavy computations to background threads, you can deliver a smooth user experience even when processing large amounts of data.</p><p>The setup might seem complex initially, but the performance benefits and improved user experience make it worthwhile for applications that handle significant data processing or computational tasks.</p><p>Ready to supercharge your React app? Start by identifying the most CPU-intensive parts of your application and consider moving them to Web Workers. Your users (and your performance metrics) will thank you!</p><p>Feel free to give the post a like if you find this post useful 😁</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97b4b210450b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Reusable Confirmation Dialog in React & Next.js]]></title>
            <link>https://medium.com/@hrupanjan/building-a-flexible-confirmation-dialog-system-in-react-or-next-js-with-typescript-1e57965b523b?source=rss-5309245d5187------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e57965b523b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react-hook-form]]></category>
            <category><![CDATA[dx-pattern]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Rupanjan Hari]]></dc:creator>
            <pubDate>Fri, 20 Jun 2025 04:51:49 GMT</pubDate>
            <atom:updated>2025-08-27T07:31:18.957Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Build a Reusable Confirmation Dialog in React &amp; Next.js using TypeScript (with Hooks &amp; Context)</h3><h4><em>Enhancing UX with Promise-based, Type-Safe Dialogs for Modern React Apps</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aqOsUCMgXU4CWdRnTozMbA.png" /></figure><p>Have you ever found yourself writing the same confirmation dialog code over and over again? Or struggled with managing multiple confirmation dialogs across your React application? Today, I’ll walk you through building a powerful, reusable confirmation dialog system that can handle everything from simple yes/no confirmations to complex form validations.</p><h3>The Problem</h3><blockquote><em>Confirmation dialogs are essential UI patterns for every React and Next.js application — from CRUD forms to destructive operations. Yet, many teams lack a reusable, type-safe approach using </em><a href="https://18.react.dev/reference/react/createContext"><em>React Context</em></a><em>, Hooks, and TypeScript for seamless user experiences.</em></blockquote><p>Most React applications need confirmation dialogs for critical actions like deleting records, submitting forms, or navigating away from unsaved changes. The typical approach involves:</p><ul><li>Creating individual dialog components for each use case</li><li>Managing state for each dialog separately</li><li>Repeating similar logic across components</li><li>Handling form validation within dialogs inconsistently</li></ul><p>This leads to code duplication, inconsistent UX, and maintenance headaches.</p><h3>The Solution: A Context-Based Confirmation Provider</h3><p>The ConfirmationProvider solves these problems by providing a centralized, promise-based confirmation system that can handle both simple confirmations and complex form-based dialogs.</p><p>Here’s how it works:</p><h4>Core Architecture</h4><p>The system consists of three main parts:</p><ol><li><strong>Context Provider</strong>: Manages dialog state and provides the confirm function</li><li><strong>Dialog Component</strong>: Renders the actual confirmation dialog</li><li><strong>Hook</strong>: Provides easy access to the confirmation functionality</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/647a7bc0423c64bd5bc3e45415fcc281/href">https://medium.com/media/647a7bc0423c64bd5bc3e45415fcc281/href</a></iframe><h4>Promise-Based API</h4><p>The genius of this system lies in its promise-based API. When you call confirm(), it returns a Promise that resolves when the user clicks “Confirm” and rejects when they click “Cancel”. This makes the code flow naturally:</p><pre>try {<br>  await confirm({ title: &quot;Delete Item&quot; });<br>  // User confirmed - proceed with deletion<br>  await deleteItem(id);<br>} catch {<br>// User cancelled - do nothing<br>}</pre><h4>State Management Deep Dive</h4><p>Let’s examine how the provider manages its internal state:</p><pre>const [options, setOptions] = useState&lt;ConfirmationProviderProps&lt;FieldValues&gt;&gt;({});<br>const [resolveReject, setResolveReject] = useState&lt;<br>[ConfirmActionFunc&lt;FieldValues&gt;?, RejectActionFunc?]<br>&gt;([]);</pre><p>The resolveReject array is particularly clever — it stores the Promise’s resolve and reject functions, allowing the component to control when the Promise settles based on user interaction.</p><h4>Form Integration</h4><p>One of the most powerful features is the seamless form integration using React Hook Form:</p><pre>const handleClick = useCallback((event: AlertEventType) =&gt; {<br>  switch (event) {<br>    case &quot;confirm&quot;:<br>      if (resolve) {<br>        if (form) {<br>          form?.trigger();<br>          if (form?.formState.isValid) {<br>            resolve(form?.getValues() as Values);<br>            handleClose();<br>          }<br>        } else {<br>          resolve();<br>          handleClose();<br>        }<br>      }<br>      break;<br>    // ...<br>  }<br>}, [resolve, reject, handleClose, form]);</pre><p>This automatically handles form validation and only resolves the Promise with form data when validation passes.</p><h4>Type Safety with Generics</h4><p>The system maintains full type safety through generous use of TypeScript generics:</p><pre>export interface ConfirmationState {<br>  confirm: &lt;Values extends FieldValues = FieldValues&gt;(<br>    options?: ConfirmationProviderProps&lt;Values&gt;<br>  ) =&gt; Promise&lt;unknown&gt;;<br>}</pre><p>This ensures that when you specify form data types, you get proper type checking throughout your confirmation flow.</p><h3>Real-World Usage Examples</h3><h4>Simple Confirmation</h4><pre>const handleDelete = async () =&gt; {<br>  try {<br>    await confirm({<br>      title: &quot;Delete User&quot;,<br>      description: &quot;This action cannot be undone.&quot;,<br>      confirmationText: &quot;Delete&quot;,<br>      buttonStyling: {<br>        confirm: { variant: &quot;destructive&quot; }<br>      }<br>    });<br>    <br>    await deleteUser(userId);<br>    toast.success(&quot;User deleted successfully&quot;);<br>  } catch {<br>    // User cancelled<br>  }<br>};</pre><h4>Form-Based Confirmation</h4><pre>const handleCreateTemplate = async () =&gt; {<br>  try {<br>    const templateData = await confirm({<br>      title: &quot;Create New Template&quot;,<br>      content: (form) =&gt; &lt;CreateTemplateForm form={form} /&gt;,<br>      defaultValues: { name: &quot;&quot;, description: &quot;&quot; },<br>      resolver: zodResolver(createTemplateSchema),<br>      confirmationText: &quot;Create Template&quot;<br>    });<br>    <br>    await createTemplate(templateData);<br>  } catch {<br>    // User cancelled or form invalid<br>  }<br>};</pre><h3>Key Benefits</h3><h4>1. Centralized Logic</h4><p>All confirmation dialog logic lives in one place, making it easy to maintain and update.</p><h4>2. Consistent UX</h4><p>Every confirmation dialog follows the same patterns and styling, providing a cohesive user experience.</p><h4>3. Type Safety</h4><p>Full TypeScript support ensures you catch errors at compile time rather than runtime.</p><h4>4. Flexible Styling</h4><p>The buttonStyling prop allows you to customize button appearance for different contexts (e.g., destructive actions get red buttons).</p><h4>5. Form Integration</h4><p>Seamless React Hook Form integration with automatic validation handling.</p><h4>6. Promise-Based Flow</h4><p>Natural async/await syntax makes confirmation flows easy to read and understand.</p><h3>Advanced Features</h3><h4>Custom Button Ordering</h4><pre>await confirm({<br>  buttonOrder: [&quot;cancel&quot;, &quot;confirm&quot;], // Cancel button first<br>  hideCancelButton: false,<br>});</pre><h4>Conditional Close Prevention</h4><pre>await confirm({<br>  allowClose: false, // Prevents ESC or backdrop click<br>  hideCloseButton: true,<br>});</pre><h4>Form Reset Control</h4><pre>await confirm({<br>  resetFormOnCompletetion: true, // Resets form after completion<br>});</pre><h3>Integration with Your App</h3><p>To use this system, wrap your app with the provider:</p><pre>function App() {<br>  return (<br>    &lt;ConfirmationProvider&gt;<br>      &lt;YourAppContent /&gt;<br>    &lt;/ConfirmationProvider&gt;<br>  );<br>}</pre><p>Then use the hook anywhere in your component tree:</p><pre>function MyComponent() {<br>  const { confirm } = useConfirmationContext();<br>  <br>  // Use confirm() as shown in examples above<br>}</pre><h3>Conclusion</h3><p>This confirmation dialog system demonstrates how thoughtful architecture can solve common React patterns elegantly. By combining Context API, Promises, and TypeScript generics, we’ve created a system that’s both powerful and easy to use.</p><p>The key insights from this implementation:</p><ul><li><strong>Promise-based APIs</strong> create intuitive async flows</li><li><strong>Context providers</strong> can manage complex state elegantly</li><li><strong>TypeScript generics</strong> enable flexible yet type-safe APIs</li><li><strong>Centralized systems</strong> reduce duplication and improve consistency</li></ul><p>Whether you’re building a simple CRUD app or a complex enterprise application, this pattern can significantly improve your confirmation dialog experience.</p><p>The idea took off from the <a href="https://www.npmjs.com/package/react-confirm">package</a> and a <a href="https://medium.com/@royeeshemesh/customizable-confirmation-dialog-in-react-js-using-hooks-context-api-and-typescript-2ab52a46228">post</a>. Now we are using this pattern across projects in react and next.js codebases. We have made two versions one using “react-hook-form” and one using “formik”.</p><p>The <a href="https://gist.github.com/hRupanjan/d5fff96cf99cccd51962d8b330e1482d">provider</a>, <a href="https://gist.github.com/hRupanjan/1b4b0ea211231488e62bfaa932c22d71">dialog</a>, <a href="https://gist.github.com/hRupanjan/9155e0e7ab39a97365b9f59af61a091d">form area</a> gist mentioned here has the complete provider setup with “react-hook-form”.</p><p>If this dialog system improved your workflow in React or Next.js, please let me know in the comments — your feedback helps the community!</p><p>Feel free to give the post a like if you find this post useful 😁</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e57965b523b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>