今日已更新 84 条资讯 | 累计 37333 条内容
关于我们

标签:#React

找到 278 篇相关文章

AI 资讯

Architectural Breakdown: Building Next-Gen Agentic Architectures: From Local RAG to Sandboxed Execut

Building Next-Gen Agentic Architectures: From Local RAG to Sandboxed Execution and BigQuery MCP The 3 AM production fire revealed a harsh truth: modern agentic systems often collapse under their own weight. A single agent processing 10K RAG queries OOM-killed an 8GB cloud instance. The culprit was not the workload but the infrastructure: @pinecone-client/vecdb with 47 transitive dependencies bloat memory with unquantized float32 embeddings. The solution was 200 lines of Python using sqlite3 , array , and heapq , with bounded queues and race condition resilience. This is the story of how we replaced dependency bloat with surgical precision. The Dependency Problem Agentic systems today face three critical bottlenecks: Vector Search : Libraries like faiss-cpu (12MB) combined with pg-vector (synchronous disk I/O) block the event loop, creating latency spikes. BigQuery : The @google-cloud/bigquery client (12MB) plus grpcio (5MB) leaks file descriptors, hitting Linux's default 1024 soft limit. Sandboxing : Docker containers consume 500MB+ per instance, making them impractical for memory-constrained environments. The root cause is always the same: unbounded resource consumption. 1M vectors at 768 dimensions in float32 consumes 3GB of memory. Synchronous I/O stalls the event loop. Unmanaged connections leak file descriptors. The Zero-Bloat RAG Engine The solution begins with a fundamental shift: replace heavy dependencies with lightweight, audited code. Our LocalRAG implementation demonstrates this approach: import sqlite3 import array import heapq import json import threading from typing import List , Tuple , Optional class LocalRAG : def __init__ ( self , db_path : str , dim : int = 768 , max_vectors : int = 1_000_000 ): self . dim = dim self . max_vectors = max_vectors self . lock = threading . Lock () self . conn = sqlite3 . connect ( db_path , isolation_level = None , check_same_thread = False ) # Enable WAL mode for concurrent reads/writes self . conn . execute ( " PR

2026-08-29 原文 →
AI 资讯

Hello World!

Hello everyone! 👋 Happy to be joining the DEV community. I’m a Computer Engineering student based in Italy. My main focus is Cybersecurity, but I strongly believe you have to know how to build a system before you can secure (or break) it. Lately, I’ve been jumping between two very different worlds: Embedded C: writing firmware, managing file systems, and building custom OLED menus for the M5Stick S3. Frontend: building web apps using Next.js and React. My workflow is a bit of a hybrid. I like to focus on the system architecture, memory management, and edge cases, while using AI tools to do the heavy lifting of writing the actual code. Then, I review everything strictly to make sure it doesn't break. I’m here to build in public, share my projects, and learn from this awesome community. What are you all currently hacking on? See you around!

2026-08-29 原文 →
AI 资讯

OWASP Mobile Top 10 — M5: Insecure Communication

Welcome to the fifth article in our OWASP Mobile Top 10 2024 series! In previous articles we covered M1: Improper Credential Usage, M2: Inadequate Supply Chain Security, M3: Insecure Authentication/Authorization, and M4: Insufficient Input/Output Validation. Today we discuss why "we already use HTTPS" isn't a sufficient answer. Introduction M5 is the most misleading item on the list, because most teams read it and move on: "We use HTTPS, this doesn't apply to us." OWASP's definition is far broader. This risk covers all aspects of getting data from point A to point B, but doing it insecurely. It encompasses mobile-to-mobile communications, app-to-server communications, or mobile-to-something-else communications. It includes all communications technologies that a mobile device might use: TCP/IP, WiFi, Bluetooth/Bluetooth-LE, NFC, audio, infrared, GSM, 3G, SMS, etc. So M5 isn't just "do you use HTTPS." It's all of this: Whether you set up TLS correctly (certificate checking, cipher selection) Whether your traffic is consistent (some endpoints HTTPS, others not) What your third-party SDKs are doing What your WebView is loading What you send over alternate channels like push notifications and SMS 💡 Key point: Just because an app uses transport security protocols doesn't mean it's implemented correctly. HTTPS is not a checkbox; it's a system that must be configured properly. A specific situation for React Native developers In React Native the network layer lives in three separate places, and most developers only think about the first: The JavaScript side — fetch , axios , XMLHttpRequest Platform configuration — ATS on iOS, Network Security Config on Android Native modules and SDKs — analytics, ads, crash reporting, payment SDKs Whatever you do on the JavaScript side, if platform configuration is loose or a third-party SDK uses plaintext HTTP, your app is exposed. OWASP Assessment Metric Value Meaning Exploitability EASY A proxy and the same network is enough Prevalence CO

2026-08-29 原文 →
开发者

A Practical Guide to React Performance

React is fast by default, until it isn't. The good news is that the vast majority of real-world performance issues trace back to a small set of patterns. Fix those, and you rarely need exotic optimizations. Measure before you optimize The first rule of performance work is to never guess. Use the React Profiler and the browser's performance panel to find what actually renders, and how often. Premature optimization Wrapping every component in memo and every value in useMemo adds complexity and can make things slower. Optimize the hot paths you have measured, not the ones you imagine. Avoid unnecessary re-renders A re-render isn't inherently bad, but cascading re-renders of expensive subtrees are. The most common culprit is passing a freshly-created object or function on every render. `// ❌ A new array + handler every render breaks memoized children function ProductList({ products }) { return ( - p.inStock)} onSelect={(id) => track(id)} /> ); } // ✅ Stabilize derived data and callbacks function ProductList({ products }) { const inStock = useMemo( () => products.filter((p) => p.inStock), [products], ); const handleSelect = useCallback((id) => track(id), []); return ; } ` Memoize the right things React.memo , useMemo and useCallback are tools for keeping referential identity stable across renders. Reach for them when: a child component is expensive to render, and it receives props that would otherwise change identity every render. Better still, let the React Compiler handle memoization for you. Adding it is a single dependency: npm install babel-plugin-react-compiler Ship less JavaScript The fastest code is the code you never send. Code-splitting and lazy loading keep the initial bundle small. `import { lazy, Suspense } from 'react'; const Editor = lazy(() => import('./Editor')); export function Panel() { return ( }> ); } ` Move work to the server With React Server Components, data fetching and heavy rendering can happen on the server, shipping only the resulting HTML an

2026-08-28 原文 →
AI 资讯

Nobody Argued For Your Stack

Last week, it came to light Cursor had mostly finished migrating from SolidJS to React . This migration happened about seven months ago. But it became a central focus of discussion following the Solid 2.0 RC release . Then yesterday, a week later, it came to my attention that the Anthropic docs example command for their large-scale migration feature is: I admit that my gut reaction was not great. Out of all the examples they could have chosen... Years of my work became a canonical example of the thing you migrate away from — in the same week we shipped the biggest release in the project's history — stung in a way I won't pretend it didn't. My second reaction was to assume that, like the other trickle-down posts I'd seen this week, this rode the same week-old news cycle. Then I checked the Internet Archive and realized this has been there since at least April 2026 . Four months before the Cursor story broke. At this point, the whole public footprint was a mention of an experiment sandwiched between bigger updates in a Cursor blog post posted in January. The kind of thing that no one outside the industry would even really pick up on. No reasoning, no benchmarks, no argument. Stop to think about what that means. I should be careful here because I can't prove anyone at Anthropic ever read that Cursor post. Nobody can. Maybe a docs writer saw the experiment. Maybe Claude drafted its own example. But think it through. Either it traveled from a buried line in one company's release notes into another company's official docs, or it needed no origin at all. It was already assumed before any public migration existed. Our industry has quietly started broadcasting conclusions where it used to transmit arguments. We couldn't have picked a worse time, because — as I'll get to — arguments are the only source that still matters. Why This Matters More Than It Used To It would be fair to ask, hasn't it always been like this? Teams cargo cult large players. Netflix or Facebook uses thi

2026-08-28 原文 →
AI 资讯

Clip Architect: MoneyPrinterTurbo as a Windows Desktop App

What Clip Architect Actually Changes About Local AI Video Generation Here's what people get wrong about a tool like this. The hard part was never really the AI writing the script. It's the plumbing around it, the part nobody photographs for the landing page. Clip Architect is a Windows desktop application that wraps the open-source MoneyPrinterTurbo pipeline (the one that turns a topic into a scripted, narrated, subtitled short video) inside a Tauri 2 shell, with a React 19 interface and a Python backend running underneath as a private local service. You give it a topic, you get an MP4 sized for TikTok, Reels or Shorts, and nothing in between gets uploaded anywhere except to whichever provider you configured, with the key you supplied yourself. No account, no subscription, no cloud render queue. Once you get that one distinction, wrapper versus engine, the rest of this holds together on its own. Why the Terminal Step Was the Real Barrier Let's look at where the friction actually sat. Upstream MoneyPrinterTurbo is a Python web app built on FastAPI with a Streamlit interface: you start it from a terminal and use it in a browser . Fine for a developer. It stops being fine the moment the person who wants the video has never opened a terminal in their life, and most people who want a video have never opened a terminal in their life. Closing that gap is the whole reason Clip Architect exists: a Tauri shell owns the window and the process lifecycle, a React frontend replaces Streamlit, and the Python backend starts and stops with the app itself, quietly, in the background. You install it, you open it, and a command line never comes up. The chain underneath doesn't change. Give it a subject, an LLM writes the script and the search keywords, stock footage or your own files supply the picture, a text-to-speech engine speaks the narration, and FFmpeg cuts the clips to the voice track, burns in subtitles, mixes background music and writes the final MP4. Every one of those stage

2026-08-27 原文 →
AI 资讯

Offline-First in React Native: Building an Auto-Sync Engine That Users Never Think About

By Shivkrishna Shah · Engineer Philosophy — @shivkrishnashah · @engineerphilosophy Your app shouldn't have a "no internet" screen. Here's the architecture I use to make mobile apps write locally, sync automatically, and survive the messy reality of field connectivity. Every mobile developer has shipped this screen at least once: a sad cloud icon and the words "No internet connection. Please try again." For consumer apps, that's an annoyance. For enterprise field apps — sales reps in hospital basements, auditors in warehouses, technicians in rural areas — it's a dealbreaker. If the app stops working when the signal drops, people stop trusting it. And once field users stop trusting an app, they go back to paper and WhatsApp. I spent the last few years building and maintaining an offline-first React Native platform used daily by field teams across multiple countries. This post is the architecture I wish someone had handed me on day one: how to structure local storage, detect connectivity, queue writes, auto-sync in the background, and avoid the two bugs that will absolutely bite you (duplicates and conflicts). Everything here is generic — I'll use Realm DB and NetInfo in the examples, but the pattern maps cleanly onto WatermelonDB, SQLite, or MMKV-backed queues. The one rule that changes everything The local database is the source of truth. The server is just a replica you happen to reconcile with. Most apps are built the other way around: the server is the truth, and the app is a thin cache over fetch() . Offline-first inverts this. Every read comes from the local DB. Every write goes to the local DB first. The network is an implementation detail that a background service worries about — never the UI. This single inversion gives you three things for free: Zero-latency UX. Saves are instant because they're local writes. No spinners on submit. Airplane-mode parity. The app behaves identically online and offline, because the UI never talks to the network. Crash safety. D

2026-08-27 原文 →
AI 资讯

What Changes When Converting SVG to React Components (JSX & TSX)

TL;DR SVG attributes like stroke-width become strokeWidth in JSX. class → className . Numeric values become {expressions} . Inline styles become objects. xmlns and XML comments are removed. The converter outputs either JSX or TSX with SVGProps . Use automation (SVGR or SVGCode) for large icon sets. Import only what you need to keep bundle sizes small. Converting an SVG file into a React component is more than just pasting markup into a .jsx or .tsx file. React uses JSX, which is stricter than HTML/XML and requires specific changes to ensure your SVG renders correctly and remains maintainable. In this post, we’ll explore every transformation that takes place—from attribute casing to TypeScript typing—so you understand exactly what our free SVG to React converter does under the hood. What Actually Changes? Kebab‑case Attributes Become camelCase SVG uses attributes like stroke-width , fill-rule , and clip-path . JSX requires property names that are valid JavaScript identifiers, so these become: SVG Attribute React JSX stroke-width strokeWidth stroke-linecap strokeLinecap stroke-linejoin strokeLinejoin fill-rule fillRule clip-path clipPath font-size fontSize stroke-dasharray strokeDasharray class Becomes className In SVG you write class="icon" , but in JSX you must use className="icon" because class is a reserved word in JavaScript. Numeric Attributes Are Converted to Expressions React treats string values differently from numbers. For numeric SVG attributes like width , height , x , y , cx , r , etc., the converter outputs {value} instead of "value" . <circle cx="12" cy="12" r="10" /> becomes: < circle cx = { 12 } cy = { 12 } r = { 10 } /> Inline Styles Become Objects If your SVG uses style="fill: red; stroke: blue;" , it must be converted to a JavaScript object: style = {{ fill : ' red ' , stroke : ' blue ' }} xmlns and Namespace Declarations Are Removed React automatically uses the correct SVG namespace, so xmlns and other XML namespace declarations are unnecessary a

2026-08-26 原文 →
AI 资讯

NutriApp: uma plataforma que conecta profissional com paciente

O NutriApp é um projeto de estudos: plataforma de saúde conectando pacientes, nutricionistas, médicos e personal trainers, cada perfil enxergando só o que sua permissão libera. Stack: React 19 + TypeScript, TanStack Start (SSR, rotas file-based e server functions), Tailwind v4 + shadcn/ui, react-hook-form + Zod para formulários tipados, TanStack Query para cache, e Lovable Cloud (Supabase) com Postgres e Row Level Security. O maior desafio foi o controle de acesso por papéis. Três tabelas centrais — profiles, user_roles e pacientes — todas com RLS ativado. Paciente lê só seus próprios registros; profissionais e administradores enxergam todos os pacientes. Pra evitar recursão de política (problema clássico de RLS), criei funções SECURITY DEFINER como has_role e is_profissional, quebrando o ciclo de verificação. Autenticação e segurança: Login por email/senha, com rota administrativa separada (/admin/login) Server functions protegidas com requireSupabaseAuth, checando papel antes de qualquer ação administrativa Validação client-side com Zod: senha entre 6-72 caracteres, email até 255, telefone opcional Usuários criados por admin já nascem confirmados e ativos, reduzindo fricção operacional Automação como diferencial: o perfil de saúde calcula IMC em tempo real e gera um plano inicial baseado no objetivo selecionado (emagrecimento, ganho de massa ou controle de patologias) — reduzindo trabalho manual do profissional. Aprendizados principais: RLS bem modelado desde o início evita gambiarra depois — pensar em papéis antes da primeira quere economiza retrabalho. Verificação de papel precisa estar no backend, nunca só na UI. Separar login de paciente/profissional do login admin simplifica segurança e UX ao mesmo tempo.

2026-08-26 原文 →
AI 资讯

The Audit's Blind Spot: I Weighed the Build, Not the Page

I published a post called "I Audited My Own Portfolio and Found 20 Problems" . It was an inventory: I went through my own site — a React 19 + Vite SPA with Sanity as the CMS — wrote down everything that was wrong with it, fixed what mattered, and put the before and after numbers next to each item. If you haven't read it, the only part that matters here is the methodology, and one line of it in particular: I went through the build output chunk by chunk in build/assets/ . I called that the step that hurts and the one most people skip. I still think that is true. It is also the step that guaranteed I would miss the largest thing wrong with the site. The step that worked Weighing the build output worked exactly as advertised. Finding 1 of that audit was an unoptimized PNG of a developer illustration on /gabriel-abreu , my contact page, 993 KB, sent to every visitor who landed there. It went to 23 KB. A second image, the cutout of me that sits in three different greetings, went from 358 KB to 45 KB. Those two are bundled assets. A component imports one: import p from " ../assets/developer-illustration.webp " ; Vite follows that import, hashes the file, and emits it into build/assets/ . After the build it is a file on disk with a size. Listing the directory finds it. Sorting the listing by size finds it first. There is no way to ship it and not have it show up in that step. So the method was sound within its domain: both of those images are bundled assets, and the step found both. On August 23 I opened the blog index in a browser and watched what it actually requested. Sixteen post covers, 9.88 MB. None of that could have appeared in the audit. Not because I was sloppy that day — because of where those bytes come from. Two lifecycles A bundled asset exists at build time. An import makes it a build input, the bundler makes it a build output, and anything that reads the build output sees it. A CMS image is never a build input. Nothing imports it. It arrives as a string in a

2026-08-26 原文 →
AI 资讯

How We Keep a Trunk-Based Pipeline From Being Reckless

Part 1 covered the mechanism: a fingerprint gate decides whether a change ships in minutes over-the-air or needs a full store release. But a gate that only checks "is this native-safe" says nothing about whether the change is good . If every merge to main can reach production within minutes, your safety net can't be a release train that gives everyone time to notice a problem before it ships — it has to be built into the pipeline itself, because there's no train to catch it on the way out. The PR gate Every pull request into main runs through the same automated gate before it's mergeable: a type check, a lint pass, an automated test suite, and end-to-end checks against a real device build. None of that is negotiable — it's the floor, not a nice-to-have. E2E is a big enough topic on its own — closing the loop between what a unit test can see and what actually happens on a phone in someone's hand — that it deserves its own dedicated post rather than a paragraph here. jobs : typecheck : run : npm run typecheck lint : run : npm run lint test : run : npm test e2e : run : npm run e2e Nothing exotic under the hood — ESLint for the lint pass, Husky for local pre-commit/pre-push hooks so the same checks catch you before CI even runs, Jest as the test runner, and React Native Testing Library for component-level tests. Popular, boring, well-documented tooling on purpose — the pipeline's value is in how these are wired together and gated, not in any one tool being clever. Feature flags are the real safety valve Here's the entry condition that makes OTA-from- main safe at all: shipping code and releasing a feature are two different actions. A merge can put new code on every user's device within minutes — that's deploy. Whether that code actually does anything visible is a separate switch, controlled by a remote feature flag, not by whether the code merged. That decoupling is what makes trunk-based development survivable. Nobody has to get the timing of a merge exactly right, bec

2026-08-26 原文 →
AI 资讯

React Form Backends Compared: Serverless Functions vs. Form-as-a-Service

React Form Backends Compared: Serverless Functions vs. Form-as-a-Service React makes building a form straightforward. What happens after onSubmit is a different question: you still need somewhere to validate, process, store, or forward the submission. Two common approaches are writing a serverless function yourself or using a hosted form backend such as onsubmit.dev (form backend). This article compares the two, using Vercel/Netlify-style functions for the DIY approach and onsubmit.dev with its React integration as the managed example. The basic problem Imagine a typical contact form: function ContactForm () { return ( < form > < input name = "email" type = "email" required /> < textarea name = "message" required /> < button type = "submit" > Send </ button > </ form > ); } The React component is only the UI. A real application usually needs backend behavior too: accepting the HTTP request validating and sanitizing input handling errors preventing abuse or spam delivering or storing the submission keeping credentials and other secrets off the client There are two broad ways to get that backend. Option 1: Build a serverless function With platforms such as Vercel and Netlify, you can create an HTTP function alongside your application and have your React form submit to it. Conceptually, the architecture looks like this: React form | v Your serverless function | +--> validation +--> email provider +--> database +--> other services The main advantage is control. Your function owns the request lifecycle, so you decide precisely how data is validated, transformed, authenticated, stored, and forwarded. If a submission needs to update PostgreSQL, call an internal API, enqueue a job, and return application-specific data, a custom backend is usually the natural solution. Serverless functions can also reduce product-level vendor lock-in. Although platforms have their own deployment conventions, HTTP handlers and their business logic are generally portable with some work. The tr

2026-08-25 原文 →
AI 资讯

Building High-Performance Web Systems & Mobile Apps: Lessons from Modern Software Engineering

Building web applications today often comes with a trade-off between feature velocity and performance. Over-reliance on heavy frameworks or unoptimized third-party plugins can quickly lead to bloated bundle sizes and poor user experience. As an engineer running DevLanka , a small web and app development studio in Sri Lanka, I’ve had the opportunity to build custom web systems and mobile applications. In this article, I want to share a few practical engineering insights on modern web performance, toolchain selection, and practical security. 1. Toolchain & Bundle Size Considerations Moving from legacy build setups to modern toolchains like Vite and React 19 significantly improves development DX (Developer Experience) and build output: Module Bundling: Vite leverages ES modules during development, resulting in faster startup times and optimized production builds. Tree-Shaking: Ensuring modern JavaScript imports are properly tree-shaken prevents unused code from shipping to the client. Rendering Strategy: For public-facing, SEO-critical pages, client-side rendering (CSR) alone may not always be ideal. Combining SSG (Static Site Generation) or SSR (Server-Side Rendering) with lightweight React components ensures proper HTML pre-rendering for search crawlers. 2. When to Use Custom Engineering vs. CMS Platforms There is no single "best" tech stack for every project. Choosing between a traditional CMS (like WordPress/Wix) and custom software engineering depends entirely on project requirements: Use a CMS when: You need rapid deployment, simple content publishing, or a standard marketing site with a limited budget. Use Custom Engineering when: You require tailored business logic, seamless API integrations, custom database schemas, or fine-grained control over execution environments. Note on Security: Custom development reduces dependency on third-party plugin vulnerability exploits, but it is not inherently immune to security risks. Custom code still requires strict adherenc

2026-08-25 原文 →
AI 资讯

I open-sourced a UI kit — then went looking for everything I got wrong about it

There's no shortage of React UI kits on npm. Search for one right now, and you'll get hundreds of results, most with the same seven button variants and a Storybook someone abandoned halfway through. So when I open-sourced brightframe — pulled out of a real coworking site I built, LAN — I didn't really want to write the usual "here's our 70 components, look how many there are" post. Component count isn't interesting. Anyone can list props and screenshot a button in five colors. What actually took time, and what I think is worth writing about, is the part that happens after the README makes a claim. "Tree-shakeable." "Server Components-safe." "Accessible." Those are three words I typed pretty confidently early on, and then, more recently, I sat down and tried to prove myself wrong on each one. This post is what that turned up. "Tree-shakeable per component" — okay, but how much, actually? Every component ships as its own entry point: import " brightframe/tokens.css " ; import " brightframe/Btn.css " ; import { Btn } from " brightframe/Btn " ; Saying "unused components add nothing to your bundle" costs nothing. I added size-limit to CI so the claim has to keep being true, not just have been true once when I wrote the sentence: Entry Minified + brotli Whole kit ( import { ... } from "brightframe" , JS) 40.13 kB Whole kit ( brightframe/style.css ) 11.83 kB One component ( brightframe/Btn , JS) 641 B One component's styles ( brightframe/Btn.css ) 890 B 641 bytes vs. 40 kilobytes. That gap is the whole reason the per-component entry points exist, and now if a refactor accidentally makes Btn drag in half the kit, the build just fails instead of me finding out from a bundle-size complaint six months later. "Server Components-safe" — this one had an actual bug in it RSC has no hook dispatcher at all. A component needs "use client" if it does one of two things in its own source: calls a hook, or wires up a DOM event handler in its own JSX. I wrote a little script ( scripts/che

2026-08-25 原文 →
AI 资讯

Architectural Breakdown: Can AI Remember What It Sees?

![ Architecture Diagram ]( https://image.pollinations.ai/prompt/high+performance+cloud+systems+Can+AI+Remember+What+It+Sees%3F+round+3?width=800&height=400&nologo=true ) # Can AI Remember What It Sees? The 3 AM OOM That Taught Me Everything About Visual Memory Systems At 2:47 AM, my production cluster dropped from 120 fps across 26 cameras down to absolute zero. The culprit was an unbounded `asyncio.Queue` that ballooned to 14 GB in 11 seconds. The fix was not more RAM. It was treating hardware constraints as first-class citizens in every design decision. --- ## The Core Lie: Statelessness by Design AI models forget by default. Transformers discard context once their attention window expires. CNNs process each frame in isolation with no persistence layer. **"Remembering" requires explicit memory injection.** You need RAM for short-term buffers, disk for long-term archives, and compressed embeddings for semantic recall. These are not interchangeable. Most engineers conflate them and pay the price in production. In practice, this distinction separates graceful degradation from hard crashes at the worst possible moment. The [ ShipMVP.tech ]( https://www.shipmvp.tech ) blueprint puts it plainly: **memory is a resource, not a feature.** --- ## Root Cause: The Three Sins That Killed My Pipeline ### Sin 1: Unbounded Queues python BEFORE: OOM in 11 seconds queue = asyncio.Queue() # No maxsize → infinite growth until death **Fix:** Cap queues to a hardware-derived bound. python AFTER: Hardware-bounded, fails fast on overflow self.queue = asyncio.Queue(maxsize=100) # ~1.5 MB at 224x224x3 uint8 **Failure walkthrough:** 1. Traffic spike hits 1200 fps and the queue swells to 800K frames (14 GB). 2. The kernel invokes swap thrashing until the OOM killer terminates the process. 3. **Lesson:** Derive `maxsize` from `(available_RAM / frame_size) * safety_factor`. Never guess. ### Sin 2: Redundant Allocations Each frame went through four separate copies: OpenCV BGR, Pillow RGB, NumPy

2026-08-25 原文 →
AI 资讯

The Evolution of Web Forms — Part 3

The Evolution of Web Forms — Part 3: React Hook Form, Validation Libraries, and Zod In Part 2, we learned that React solved the problem of manually updating the DOM. Instead of writing: emailError . textContent = " Email already exists " ; emailInput . setAttribute ( " aria-invalid " , " true " ); React allowed us to describe the interface from state: < input aria-invalid = { Boolean ( errors . email ) } /> { errors . email && ( < p > { errors . email } </ p > )} However, React did not automatically manage: Form values Validation errors Touched fields Dirty fields Submission state Reset behavior Dynamic fields Backend errors Performance Developers still had to build those features manually. That created the need for form-management libraries. This part covers: React Hook Form’s philosophy and architecture React Hook Form’s core APIs Validation libraries React Hook Form with Zod and TypeScript By the end, we will build a production-style registration form using: React + TypeScript + React Hook Form + Zod + An API layer Stage 9: React Hook Form Deep Dive React Hook Form is not simply a shorter way to write controlled React forms. It uses a different architectural philosophy. A traditional controlled input stores its value in React state: const [ email , setEmail ] = useState ( "" ); < input value = { email } onChange = { ( event ) => { setEmail ( event . target . value ); } } /> Every keystroke produces a state update: User types ↓ onChange runs ↓ setEmail runs ↓ Component renders again ↓ Input receives the new value React Hook Form prefers native, uncontrolled inputs when possible. < input { ... register ( " email " ) } /> The browser stores the current value inside the input element. React Hook Form registers the input, listens to its events, tracks relevant form state, and reads its value when required. React Hook Form’s official documentation describes register() as the mechanism that connects an input to validation, value tracking, and submission. Controlled vers

2026-08-24 原文 →
AI 资讯

Architectural Breakdown: We fixed the eval platform we're competing on: a TypeError that crashed thr

We Fixed the Eval Platform: The TypeError That Took Down Three Benchmark Pipelines At 3 AM, Sentry lit up with TypeError: Cannot read property 'map' of undefined . Three benchmark pipelines crashed. Not a memory leak, not a segfault, but a race condition hiding behind a TypeError, turning a high-stakes eval run into chaos. Here is how we resolved it, with no fluff. The Root Cause: Async Data Meets Blind Faith in .map() The error trace pointed to evaluator.ts:42 , where .map() assumed inputData.metrics would always exist. The junior dev tested with clean data, but in production, fetchBenchmarkData() (async) and evaluatePipeline() (sync) were racing . At 100+ RPS, metrics was often undefined . The Offending Code: const results = inputData . metrics . map ( metric => computeScore ( metric )); Why It Failed: Race Condition : inputData was fetched asynchronously, but evaluatePipeline() treated it as synchronous. OOM Risk : Unbounded .map() on 10K+ metrics could exhaust 8GB RAM. Worker Starvation : No concurrency limits led to thread pool exhaustion. The Fix: Guard Clauses, Bounded Queues, and Pragmatism Step 1: Fail Fast, Fail Loud Added zero-overhead runtime checks to reject bad data early: // eval-platform/core/evaluator.ts import { isNullOrUndefined } from ' ../utils/guards ' ; async function evaluatePipeline ( inputData : BenchmarkInput ): Promise < EvaluationResult > { if ( isNullOrUndefined ( inputData ?. metrics )) { throw new Error ( ' EVAL_400: metrics missing ' ); } // Proceed only if data is valid } Why? Stops TypeError crashes immediately. Cost: 1-2 CPU cycles. Negligible. Step 2: Chunked Processing for 8GB RAM Original code processed all metrics at once, causing OOM crashes. Fixed with 100-item chunks: const CHUNK_SIZE = 100 ; // 100 items ≈ 10MB peak memory const results : number [] = []; for ( let i = 0 ; i < inputData . metrics . length ; i += CHUNK_SIZE ) { const chunk = inputData . metrics . slice ( i , i + CHUNK_SIZE ); results . push (... chunk . map

2026-08-24 原文 →
AI 资讯

App-like UX in Next.js 16.3

Building App-like Experiences with Next.js 16.3 A hands-on look at how Next.js 16.3 helps apps feel fast and smooth, more like a single-page app, without losing the benefits of server rendering. Using four demo apps, it shows how features like Instant Navigations, Cache Components, Partial Prefetching, optimistic updates, Suspense streaming, offline retry, and View Transitions work together in real apps ⚡️ Sponsor: Arcjet AI compliance controls Protect your AI applications from prompt injection, PII leaks, and unauthorized tool calls. 📙 Articles / Tutorials / News Next.js team AMA The Next.js team opened the floor to community questions and covered a lot of ground. The AMA focused on Next.js 16.3, performance, caching, App Router, React Server Components, and upgrading apps, along with some insight into how the team works on the framework Coordinating Optimistic Updates in Next.js This guide shows how useActionState and useOptimistic can work together to keep the UI updated right away, save changes in the right order, and roll back cleanly if something fails Using next/root-params in Next.js 16.3 The new next/root-params API lets Server Components read top-level params like [locale] from deep in the tree, which makes next-intl much easier to use Docs for React's new browser() API The docs for React's new browser() API are now available in Canary. You can pass it to use() , where it suspends to the nearest Suspense boundary on the server, then renders normally in the browser 📦 Projects / Packages / Tools Better Auth 1.7 A big release for Better Auth, especially around OAuth, OpenID Connect, SCIM, SSO, MCP, and device login flows. The main theme here is stronger auth, better enterprise identity support, and more standards-based ways for apps and devices to sign in and get access Next 16 Calendar "Flow" A calendar and booking demo exploring Async React, Cache Components, Partial Prefetching, and View Transitions with Next.js 16.3, React 19, Tailwind CSS v4, and Prisma.

2026-08-23 原文 →
开发者

Cómo solucionar el error \"Text content does not match server-rendered HTML\" en Next.js App Router

Cómo solucionar el error "Text content does not match server-rendered HTML" en Next.js App Router Este error ocurre cuando el HTML generado en el servidor (SSR/SSG) no coincide con el árbol de React que se construye durante la primera renderización en el navegador (hydration). Es un problema crítico de consistencia de estado que rompe la experiencia de usuario y puede causar comportamientos impredecibles. 🔍 Causa raíz (diagnóstico técnico) En tu caso, el error está relacionado con contenido dinámico que varía entre renderizado del servidor y renderizado del cliente , probablemente causado por: Uso de Date() , Math.random() , localStorage , window , o APIs del navegador directamente en el render . Uso de typeof window !== 'undefined' como condición de renderizado (no es idempotente entre SSR y CSR). Metaetiquetas de detección automática de iOS ( format-detection ) que inyectan nodos <a> en tiempo de ejecución. Extensiones del navegador (especialmente en desarrollo) que modifican el DOM. Librerías CSS-in-JS mal configuradas que inyectan clases o estilos dinámicos en CSR. ⚠️ Nota crítica : Next.js App Router no permite el uso de useEffect para evitar el mismatch en el primer render — el mismatch debe prevenirse , no suprimirse . ✅ Solución definitiva (pasos verificados) Paso 1: Elimina toda lógica no determinista del render NUNCA uses lo siguiente directamente en el cuerpo del componente: // ❌ Evitar const now = new Date (); // ❌ const isClient = typeof window !== ' undefined ' ; // ❌ const randomId = Math . random (); // ❌ const theme = localStorage . getItem ( ' theme ' ); // ❌ ✅ Reemplaza con: // ✅ Usar `useEffect` para *actualizar* el estado, no para *determinar* el render inicial import { useState , useEffect } from ' react ' ; export default function Component () { const [ time , setTime ] = useState < string > ( '' ); // Inicializa con valor seguro (ej. string vacío o placeholder) useEffect (() => { setTime ( new Date (). toISOString ()); }, []); return < time d

2026-08-23 原文 →