惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
aimingoo的专栏
aimingoo的专栏
Microsoft Security Blog
Microsoft Security Blog
NISL@THU
NISL@THU
T
Threatpost
T
The Exploit Database - CXSecurity.com
T
Threat Research - Cisco Blogs
S
Securelist
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
人人都是产品经理
人人都是产品经理
B
Blog RSS Feed
S
Secure Thoughts
MyScale Blog
MyScale Blog
O
OpenAI News
P
Palo Alto Networks Blog
美团技术团队
C
Cyber Attacks, Cyber Crime and Cyber Security
TaoSecurity Blog
TaoSecurity Blog
量子位
L
Lohrmann on Cybersecurity
G
GRAHAM CLULEY
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
Tailwind CSS Blog
Know Your Adversary
Know Your Adversary
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Simon Willison's Weblog
Simon Willison's Weblog
宝玉的分享
宝玉的分享
PCI Perspectives
PCI Perspectives
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
C
Cybersecurity and Infrastructure Security Agency CISA
T
Tenable Blog
I
InfoQ
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Microsoft Azure Blog
Microsoft Azure Blog
Recent Announcements
Recent Announcements
S
Security @ Cisco Blogs
S
Schneier on Security
B
Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
The Cloudflare Blog
AWS News Blog
AWS News Blog
IT之家
IT之家
V
Vulnerabilities – Threatpost
The Hacker News
The Hacker News
H
Heimdal Security Blog
I
Intezer
A
Arctic Wolf
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
H
Help Net Security
W
WeLiveSecurity

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Why modal.open() should return Promise<TResult>, not Promise<any>
Oleksii Kyrychenko · 2026-06-12 · via DEV Community

How treating modals as typed async operations eliminates boolean state, callback chains, and runtime surprises in React apps.

React applications often treat modals as UI details.

A boolean flag. A conditional render. An onClose callback.

That works fine for one dialog.

But real products have modals that are actually business flows:

  • confirm this destructive action
  • rename this entity and return the new name
  • pick a date range and apply it
  • resolve a conflict before continuing
  • complete a wizard step before the next one unlocks

These flows need more than a boolean.

They need typed input, typed output, and a way to await the result — just like any other async operation in your app.

const result = await modal.open(renameReportModal, {
  reportId: report.id,
  currentName: report.name,
});

if (result.status === "renamed") {
  await renameReport({ id: report.id, name: result.name });
}

That is the idea behind:

npm install @okyrychenko-dev/react-modal-manager zustand

A modal lifecycle manager. Not a component. Not a design system.
A typed async contract between your app logic and your dialog UI.


The problem with traditional modal state

In most React apps, modal state starts locally:

function ReportsPage() {
  const [isRenameOpen, setIsRenameOpen] = useState(false);

  return (
    <>
      <button onClick={() => setIsRenameOpen(true)}>Rename</button>
      {isRenameOpen && (
        <RenameModal onClose={() => setIsRenameOpen(false)} />
      )}
    </>
  );
}

And then real requirements arrive:

const [isRenameOpen, setIsRenameOpen] = useState(false);
const [isDeleteOpen, setIsDeleteOpen] = useState(false);
const [isShareOpen, setIsShareOpen] = useState(false);

const [renameTarget, setRenameTarget] = useState<Report | null>(null);
const [deleteTarget, setDeleteTarget] = useState<Report | null>(null);
const [shareTarget, setShareTarget] = useState<Report | null>(null);

The UI is not the problem.

The orchestration is:

  • Where does the modal state live?
  • How do we pass typed input into it?
  • How do we get a typed result back?
  • How do we open it from a command palette, keyboard shortcut, or service?
  • How do we avoid leaking state between tests?

The Promise<any> problem

Several modal libraries already have a promise-based API. For example, @ebay/nice-modal-react is mature, popular, and widely used.

But the result type is often weak:

// nice-modal-react
const result = await NiceModal.show("rename-report", data);
// result is: any

result.nme;       // ✅ TypeScript is silent — typo undetected
result.whatever;  // ✅ TypeScript is silent — doesn't exist
result.name;      // ✅ Fine — but compiler can't help you verify it

When result is any, TypeScript cannot verify the contract between the caller and the modal.

With a typed modal definition, the modal becomes the contract:

// @okyrychenko-dev/react-modal-manager
const result = await modal.open(renameReportModal, data);
// result is: { status: "renamed"; name: string } | { status: "cancelled" }

result.nme;       // ❌ Property 'nme' does not exist on type...
result.whatever;  // ❌ Property 'whatever' does not exist on type...
result.name;      // ✅ Only available after narrowing result.status === "renamed"

The difference is not cosmetic. In long-lived codebases, untyped modal results are a source of silent runtime bugs and refactoring accidents.


Design goals

The library was built around a few constraints:

  • modal input and result should be inferred by TypeScript
  • modal state should be scoped to a provider, not leaked globally
  • the UI layer should stay replaceable
  • opening a modal should work both inside and outside React components
  • closing, dismissing, and rejecting should be explicit lifecycle outcomes

Basic usage

Wrap your app with ModalProvider, then call useModalManager() from any descendant:

import {
  ModalProvider,
  useModalManager,
} from "@okyrychenko-dev/react-modal-manager";

function App() {
  return (
    <ModalProvider>
      <ReportsPage />
    </ModalProvider>
  );
}

function DeleteButton() {
  const modal = useModalManager();

  async function handleDelete() {
    const { confirmed } = await modal.confirm({
      title: "Delete report?",
      description: "This action cannot be undone.",
      confirmText: "Delete",
      variant: "danger",
    });

    if (!confirmed) return;

    await deleteReport();
  }

  return <button onClick={handleDelete}>Delete</button>;
}

No lifted state. No callback chains. The flow reads sequentially.


Defining a typed modal

A modal is a React component with typed input and typed result:

import {
  createModal,
  type ModalComponentProps,
} from "@okyrychenko-dev/react-modal-manager";

interface RenameReportInput {
  reportId: string;
  currentName: string;
}

type RenameReportResult =
  | { status: "renamed"; name: string }
  | { status: "cancelled" };

function RenameReportModal({
  input,
  close,
}: ModalComponentProps<RenameReportInput, RenameReportResult>) {
  const [name, setName] = useState(input.currentName);

  return (
    <dialog open>
      <h2>Rename report</h2>
      <input value={name} onChange={(e) => setName(e.target.value)} />
      <button onClick={() => close({ status: "cancelled" })}>Cancel</button>
      <button onClick={() => close({ status: "renamed", name })}>Rename</button>
    </dialog>
  );
}

export const renameReportModal = createModal<RenameReportInput, RenameReportResult>({
  component: RenameReportModal,
});

Now every call site gets full inference:

const result = await modal.open(renameReportModal, {
  reportId: report.id,
  currentName: report.name,
});

if (result.status === "renamed") {
  await renameReport({ id: report.id, name: result.name });
}

TypeScript knows what input the modal requires, what shape can be passed to close(), and how to narrow the result. If you rename a field in RenameReportResult, every call site breaks at compile time — not at runtime.


The open handle

modal.open() returns a ModalHandle — a Promise with two extra properties:

const handle = modal.open(renameReportModal, {
  reportId: report.id,
  currentName: report.name,
});

// Identify this specific instance
console.log(handle.instanceId);

// Dismiss it from outside the modal component — from a timeout, a shortcut, another action
handle.dismiss();

// Still a regular Promise
const result = await handle;

This is useful when the caller needs to control the lifetime of the modal independently of the result — for example, closing a progress dialog when a background job finishes.


Opening modals from non-React code

Sometimes a modal needs to open from outside the React tree: a keyboard shortcut handler, a command palette, a domain service, a Redux thunk.

createModalRegistry creates a typed registry that can be called from anywhere:

// modals.ts
import { createModal, createModalRegistry } from "@okyrychenko-dev/react-modal-manager";

export const modals = createModalRegistry({
  renameReport: createModal({ component: RenameReportModal }),
  deleteReport: createModal({ component: DeleteReportModal }),
});

// App.tsx — bind it to the provider
<ModalProvider registry={modals}>
  <App />
</ModalProvider>

// keyboard-shortcuts.ts — call it from anywhere
document.addEventListener("keydown", (e) => {
  if (e.key === "F2" && currentReport) {
    void modals.open("renameReport", {
      reportId: currentReport.id,
      currentName: currentReport.name,
    });
  }
});

The key is type-checked. The input is inferred from the registered modal. The result is inferred too — no string-based API, no Promise<any>.


Provider-scoped isolation

Modal state is isolated per ModalProvider. Each provider owns its own internal store — no module-level singleton.

<ModalProvider>
  <AdminApp />
</ModalProvider>

<ModalProvider>
  <PublicPreview />
</ModalProvider>

These two trees do not share modal state. This matters for:

  • tests — each test mounts its own provider, no cross-test leakage
  • Storybook — each story is isolated
  • SSR and Next.js App Router — no shared state between requests
  • micro-frontends — multiple app roots on the same page

Built-in confirm

modal.confirm() ships out of the box:

const { confirmed, reason } = await modal.confirm({
  title: "Discard changes?",
  description: "Your edits will be lost.",
  variant: "warning",
});

if (confirmed) {
  discard();
} else {
  console.log(reason); // "cancel" | "dismiss"
}

The result is a discriminated union — no need to check typeof or cast anything.

The built-in confirm component includes an accessibility baseline:

  • role="dialog" with aria-modal, aria-labelledby, aria-describedby
  • Focus moves to the dialog on open and returns to the trigger on close
  • Tab / Shift+Tab are trapped within the dialog
  • Escape dismisses (unless dismissible: false)
  • danger variant focuses the cancel button by default — an accidental Enter never confirms a destructive action

It ships without styling. Production apps usually swap it for a design system version via confirmModal prop:

const myConfirm = createModal<ConfirmModalParams, ConfirmModalResult>({
  component: MyDesignSystemConfirm,
});

<ModalProvider confirmModal={myConfirm}>
  <App />
</ModalProvider>


UI-agnostic rendering

The library never prescribes how a modal should look. A renderer boundary lets you plug in any design system:

// Tailwind
function AppModalRenderer({ children, modal }: ModalRendererProps) {
  return (
    <div
      data-status={modal.status}
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/50
                 transition-opacity data-[status=closing]:opacity-0"
    >
      <div className="w-full max-w-md rounded-lg bg-white p-6 shadow-xl">
        {children}
      </div>
    </div>
  );
}

<ModalProvider closeDelayMs={150} renderer={AppModalRenderer}>
  <App />
</ModalProvider>

When closeDelayMs > 0, a closed modal moves to status: "closing" before being removed — your CSS transition runs, then the instance is unmounted. Your promise settles immediately; the visual exit happens independently.

shadcn/ui works the same way. In a production app, wire onOpenChange to dismiss the modal when the user closes the dialog from the UI:

function ShadcnRenderer({ children, modal }: ModalRendererProps) {
  const manager = useModalManager();

  return (
    <Dialog
      open={modal.status === "open"}
      onOpenChange={(open) => {
        if (!open) {
          manager.dismiss(modal.instanceId);
        }
      }}
    >
      <DialogContent>{children}</DialogContent>
    </Dialog>
  );
}


Compared to nice-modal-react

@okyrychenko-dev/react-modal-manager nice-modal-react
Result typing Promise<TResult>, fully inferred Promise<any>
State scope Isolated per ModalProvider Centralized provider/global-style modal store
Open from non-React code Typed registry Id-based global-style API
Built-in confirm Typed + accessibility baseline Not the main focus
UI coupling UI-agnostic renderer Integration helpers for specific libs
Maturity New 3+ years, battle-tested, large ecosystem

nice-modal-react is a genuinely good library. If you want a mature modal manager with broad ecosystem usage and id-based convenience, it is a great choice.

This library takes a different trade-off: stricter types and explicit isolation over convenience and ecosystem breadth.


When this is a good fit

  • Your modals return meaningful, typed results
  • You want to await modal flows inline
  • You want TypeScript to catch call-site mismatches at compile time
  • You use Next.js App Router, SSR, Storybook, or micro-frontends
  • You need to open modals from action maps, services, or keyboard shortcuts
  • You want UI-library agnosticism at the core

When it is not

  • You have only one or two simple dialogs — useState is enough
  • Your modals do not return structured results
  • You want a fully styled modal component out of the box
  • You prefer a global string-based API over typed definitions
  • You do not want a Zustand peer dependency

Final thoughts

A modal that asks "Are you sure?" before a destructive action is not a UI detail.

It is a checkpoint in a business flow. It has an outcome. That outcome affects what happens next.

Treating it as a boolean flag — or as Promise<any> — throws away information the compiler could use to keep your code correct.

const result = await modal.open(someModal, input);

Simple at the call site. Strict at the type level. Isolated at the provider boundary.

That is the bet this library makes: modal flows should be as type-safe as the rest of your application logic.


Try it out:

npm install @okyrychenko-dev/react-modal-manager

If you like the approach, drop a ⭐️ on the GitHub repo and let me know what you think in the comments! 👇