AI 资讯
Building a Resilient Real-Time Chat System with WebRTC, Faye, and WebSockets: A Practical End-to-End
Building a Resilient Real-Time Chat System with WebRTC, Faye, and WebSockets: A Practical End-to-End Building a Resilient Real-Time Chat System with WebRTC, Faye, and WebSockets: A Practical End-to-End Tutorial In this tutorial you’ll build a small, resilient real-time chat system that works across browsers, mobile devices, and constrained networks. You’ll learn how to architect a client/server model with signaling, leverage WebRTC data channels for peer-to-peer messaging when available, and fall back to a robust WebSocket-based relay when direct peer connections fail. The focus is on practical patterns, testable code, and observability to keep a live chat running under load or flaky networks. Key takeaways Understand when to use WebRTC data channels vs. WebSocket relays for real-time chat Implement a signaling server to establish WebRTC connections safely and efficiently Build a resilient message delivery pipeline with idempotent processing and retry semantics Instrument the system for latency, jitter, and message loss to avoid silent failures Test end-to-end flows with simulated network conditions and automated resilience tests Overview of architecture Clients (web and mobile) connect to a signaling server to negotiate WebRTC peers and/or WebSocket sessions. If a direct WebRTC peer connection is possible, use a data channel for low-latency chat messages. If WebRTC is blocked (firewalls, NAT), route messages through a relay server using WebSockets. The relay can also bridge peers that can’t connect directly. A lightweight message store (in-memory for demo, with an optional Redis-backed queue in production) provides at-least-once delivery guarantees and retry capabilities. Observability: metrics for connection attempts, handshake times, message delivery latency, retry counts, and error rates. Tracing spans help diagnose cross-service flows. Tech stack (example) Frontend: TypeScript, WebRTC DataChannel, WebSocket Backend: Node.js with Express for signaling API, ws or
AI 资讯
I Replaced Rive, GSAP, and Lottie with One Visual Runtime. Here's What Happened to Our React App.
Six months ago, our React app's animation stack looked like a dependency graveyard: Rive for interactive vector graphics GSAP for timeline-based UI animations Lottie for JSON animations imported from design Framer Motion for React-specific transitions Plus a few hand-rolled CSS animations for good measure Four tools. Four mental models. Four runtime dependencies. And a growing gap between what designers shipped and what developers could maintain. We consolidated everything into a single visual runtime. Here's what actually happened. The Problem Nobody Talks About Animation tools are great in isolation. The cracks appear when you need a single component to do multiple things: A button that plays a Rive animation on hover, transitions with Framer Motion on click, and shows a Lottie loading state A card that animates into view with GSAP , has hover states in Rive , and a pressed state in CSS A form that validates with Framer Motion shake animations, loads with Lottie spinners, and succeeds with a Rive celebration Each tool handles its piece. None of them talk to each other. You end up writing coordination code that's more complex than the animations themselves. What We Switched To We moved to ExodeUI — a visual runtime that combines state machines with vector rendering. Instead of four tools plus coordination code, we have: One editor where designers define visual states as nodes One file format that stores both appearance and behavior One export that generates production React components One runtime that renders everything natively The pitch sounds almost too clean. We were skeptical too. What We Actually Gained 1. Eliminated three runtime dependencies Removing Rive's .riv player, Lottie's JSON player, and GSAP's timeline engine from our bundle saved roughly 180KB gzipped. Not life-changing for desktop, but noticeable on mobile. 2. Design files became production code The biggest win wasn't technical — it was process. Our designer builds components in ExodeUI with stat
AI 资讯
Show DEV: Obex, a faith-based self-control app with streak tracking and blockers
I’m building Obex, a faith-rooted self-control app for men who want to quit porn and stay consistent with daily discipline. The stack is Expo / React Native, with a web landing page and a desktop blocker companion. Core features: Streak tracking and rank progression Panic Mode for urgent moments Accountability partners Blocker support on desktop Christian-focused language and reminders The goal is to make the product feel practical rather than preachy. People usually respond better to clear feedback loops, a visible streak, and a calm recovery path after setbacks. If you want to see it or give feedback, the site is here: https://obex.so
开发者
React + Mapbox GL JS: Custom Markers, Popups, and Bounds-Based Data Fetching
React + Mapbox GL JS: Custom Markers, Popups, and Bounds-Based Data Fetching If you've added a Mapbox map in a React app before, you've probably hit a wall pretty quickly: Mapbox GL JS manages its own DOM, and React manages a virtual DOM, and getting the two to play nicely takes some thought. Markers and popups are a great example of this tension — they're imperative APIs in a world where you want declarative components. This post walks through a pattern I've landed on for wrapping mapboxgl.Marker and mapboxgl.Popup in composable React components, and combining them with bounds-based data fetching to build something like a real estate or earthquake explorer map — where the data on the map updates as you pan and zoom. Here's what we'll cover: Wrapping mapboxgl.Marker in a React component that handles its own lifecycle Using createPortal to render custom marker content in React Fetching data from an API using the map's current bounding box Tracking an active marker with React state Wrapping mapboxgl.Popup in a component If you want to see the finished product first, the source code is on GitHub . The Core Challenge: Two DOMs Before we get into the code, it's worth understanding why this requires a pattern at all. When you use React's normal component tree, React controls the DOM. But mapboxgl.Marker also creates and manages DOM nodes — it places an element on the map at a specific geographic coordinate, handles repositioning as you pan, and removes itself cleanly when you're done with it. The approach here is to use React to manage the lifecycle of each marker (mount when data arrives, unmount when data goes away), while letting Mapbox handle the positioning . We use React's createPortal to render JSX content into a DOM node that we hand off to Mapbox. The example discussed below is a map that fetches earthquake data for the current viewport, displaying a custom Marker and Popup for each. As you move the map and the bounds change, new data is fetched and the Markers a
AI 资讯
From Pills to Pixels: Building an Intelligent Home Pharmacy Manager with YOLOv8 and CLIP 💊✨
We’ve all been there: staring at a messy medicine cabinet, wondering which box is for allergies and which one expired in 2022. In the world of Computer Vision and AI Healthcare , digitizing physical assets is a classic challenge. Today, we're building a "Medicine Box Expert"—a sophisticated pipeline that uses YOLOv8 for precision detection and OpenAI CLIP for multimodal understanding to turn a pile of pills into a searchable digital database. By the end of this tutorial, you'll understand how to bridge the gap between raw pixels and structured medical data. We are moving beyond simple classification; we are building a robust system capable of handling complex lighting, varied angles, and the tiny typography common in pharmaceutical packaging. The Architecture: A Multi-Stage Vision Pipeline To achieve high accuracy, we don't rely on a single model. Instead, we use a "Detect-Extract-Embed" workflow. graph TD A[User Uploads Image] --> B[YOLOv8: Box Detection] B --> C{Box Found?} C -- Yes --> D[Crop & Preprocess] C -- No --> E[Error: No Box Detected] D --> F[Tesseract OCR: Text Extraction] D --> G[OpenAI CLIP: Visual Embedding] F & G --> H[SQLite Query: Semantic Search] H --> I[Result: Drug Info & Dosage] Prerequisites Before we dive into the code, ensure you have the following tech_stack installed: YOLOv8 : For real-time object detection. OpenAI CLIP : To handle semantic image-text matching. Tesseract OCR : For reading the fine print on the boxes. SQLite : To store and query our medicine metadata. pip install ultralytics transformers torch pytesseract Step 1: Detecting the Medicine Box with YOLOv8 First, we need to locate the medicine box within the frame. A generic YOLOv8 model (like yolov8n.pt ) is surprisingly good at detecting "books" or "cell phones," but for the best results, you should fine-tune it on the Open Images Dataset specifically for "Box" or "Medical Packaging." from ultralytics import YOLO import cv2 # Load the model model = YOLO ( ' yolov8n.pt ' ) def
开发者
Is This How We'll Build Websites Soon? (webMCP Live Demo 🚀)
A few years ago, we started adapting our websites for mobile devices. Then we adapted them for...
AI 资讯
Cómo solucionar el error \"Text content does not match server-rendered HTML\" en Next.js
Cómo solucionar el error "Text content does not match server-rendered HTML" en Next.js Este error ocurre cuando el HTML generado en el servidor (SSR) no coincide con el árbol de React que se construye durante la hidratación inicial en el navegador. Es un problema crítico que rompe la experiencia de usuario y puede causar comportamientos impredecibles. Causa raíz En tu caso, el error está relacionado con contenido dinámico que varía entre renderizado del servidor y renderizado del cliente , probablemente por: Uso de Date() o new Date() en el renderizado (ej. fechas de eventos como JUN 9 , JUN 11 , etc.) Uso de typeof window !== 'undefined' o APIs del navegador directamente en el render Metaetiquetas o scripts que modifican el DOM antes de la hidratación (como iOS detectando fechas como enlaces) Configuración incorrecta de librerías CSS-in-JS o Edge/CDN que modifiquen el HTML Solución definitiva (pasos) ✅ Paso 1: Aisla el contenido dinámico con suppressHydrationWarning Si el contenido que varía es intencional (como fechas de eventos), envuelve solo el elemento problemático con suppressHydrationWarning={true} : // app/page.tsx o app/events/page.tsx export default function EventsPage () { const events = [ { name : ' NEXT.JS NIGHTS ' , date : new Date ( ' 2024-06-09 ' ) }, { name : ' AMS ' , date : new Date ( ' 2024-06-11 ' ) }, { name : ' LDN ' , date : new Date ( ' 2024-06-18 ' ) }, ]; return ( < div > < h2 > VIEW EVENTS </ h2 > < ul > { events . map (( event , i ) => ( < li key = { i } > < strong > { event . name } </ strong > { /* ✅ Solo este elemento usa suppressHydrationWarning */ } < time dateTime = { event . date . toISOString () } suppressHydrationWarning > { event . date . toLocaleDateString ( ' en-US ' , { month : ' short ' , day : ' numeric ' }) } </ time > </ li > )) } </ ul > </ div > ); } ⚠️ Importante : suppressHydrationWarning solo funciona en el elemento inmediato, no en hijos. Usa span , time , div , etc., no en contenedores grandes. ✅ Paso 2: Evita Da
AI 资讯
Stop Shipping 20 Locale Files in React Native: On-Device Translation for Dynamic Language Packs
Stop Shipping 20 Locale Files in React Native: On-Device Translation for Dynamic Language Packs Internationalization in mobile apps usually starts clean and then gets expensive. At first, you keep a couple of JSON files: en.json es.json fr.json That works when your product is small and the set of languages is stable. It breaks down when: you want to support many languages the product team keeps changing copy translated files drift out of sync some languages are only partially used you do not want to run every string through a server-side translation pipeline This is the problem @tcbs/react-native-language-translator is trying to solve. It lets a React Native app keep a source language, translate missing keys on device, and cache the generated language pack locally. Package: @tcbs/react-native-language-translator The problem Many React Native apps treat localization as a static asset problem: keep one JSON file per language ship all of them in the app update all of them whenever English changes That model has real costs. 1. Translation files become operational debt Every new feature adds more keys. Every copy change forces translators to update multiple locale files. Over time, the translation layer becomes a maintenance queue. The result is predictable: missing keys stale translations untranslated fallback strings inconsistent release quality across languages 2. Shipping many locales is wasteful Most users only need one target language. But many apps ship every locale anyway. That increases bundle size and creates a lot of dead weight for users who will never use most of those files. 3. Dynamic product copy is hard to localize well If your app changes quickly, static translation files lag behind. Teams either accept stale translations or build a backend workflow to keep everything synchronized. That is often more infrastructure than the app actually needs. 4. Server-side translation is not always the right tradeoff Calling a translation API at runtime introduces: la
AI 资讯
Cursor vs Offset Pagination: A Frontend Engineer's Perspective in 2026
We talk about pagination as if it's purely a backend concern – the database does the heavy lifting, the API returns pages, and the frontend just renders them. But in 2026, that mental model is outdated. The frontend now owns more of the data-fetching lifecycle than ever: server components prefetch, client caches hydrate, optimistic updates mutate, and streaming responses trickle in chunk by chunk. The choice between cursor pagination and offset pagination has real consequences for how you write your React components, how your cache behaves, how scroll feels on the phone, and what happens when a user navigates back. This post is about those tradeoffs – from the frontend seat. The Landscape Has Changed A few things are different in 2026 that make this conversation more nuanced than it was three or four years ago: React Server Components are mainstream. Data fetching happens on the server in many apps, which shifts where pagination state lives and how navigation works. TanStack Query is the de-facto standard for client-side async state, with first-class infinite query support baked in. The "infinite scroll vs pagination" debate is mostly settled — infinite scroll wins for feeds and content-heavy apps; numbered pages win for dense data tables. Your pagination strategy should serve that decision, not fight it. LLM-powered search and filtering are becoming common, and those use cases have their own quirks around pagination stability. Edge caching and CDN-level pagination mean that certain offset-paginated responses can be cached by URL – a genuine advantage offset still holds. What Frontend Engineers Actually Care About When you strip away the SQL theory, here's what the pagination choice actually affects on the frontend: 1. Cache Key Design With offset pagination, the cache key is simple and predictable: posts?page=3&limit=20 . Every page is independently cacheable by URL — your CDN loves this. TanStack Query, SWR, and Apollo all handle this naturally. // Offset — clean,
开发者
React State Management: When to Use useState, Context, or Zustand
Here's a conversation I've had more than once. A developer is building a React app. It starts...
AI 资讯
Turn Figma frames into clean React, Angular, Vue, or HTML with AI — meet PixToCode
PixToCode is a new Figma plugin that turns the frames you've already designed into production-ready code with AI — React, Angular, Vue, or HTML, all Tailwind-first. Just published on the Figma Community: figma.com/community/plugin/1641790551381890223/pixtocode What it does Select one or more frames in Figma, pick a framework, click Generate. About 10 seconds later you have clean code that uses the exact colors, spacing, typography, and layout from your file — not generic Tailwind utility soup. Highlights: 4 frameworks — React (TypeScript), Angular (standalone + Signals), Vue 3, or semantic HTML5. All Tailwind-first. UI library presets — shadcn/ui, Material UI, Chakra, Ant Design on React, Angular Material on Angular. Output uses the real components , not generic divs. Refine with plain English — type "make the button rounded" or "use green for the active tab" and the AI rewrites the component in place. Multi-frame batch — select up to 5 frames, get them all in one pass. Variants → typed props — a Figma Component Set with Primary / Secondary / Disabled becomes one typed prop-driven component, not three duplicate files. Live browser preview — see the generated component rendered in a sandboxed tab before pasting it into your project. Cloud history — every generation saved to your account, synced across devices. How it works Get a free license key at pixtocode.com (5 free generations, no credit card). Install the plugin from the Figma Community. Paste the key into the plugin's license field. Select a frame, choose a framework, click Generate. Copy the code straight into your project. That's the whole flow. Pricing Free — 5 generations on signup Pro — $20/month for 100 generations Power — $39/month for 250 generations Team — $99/month, 5 seats, 600 shared generations (scales to 10 seats) All paid plans have a 7-day refund guarantee. Tips for best results Frames with auto-layout , named layers , and consistent design tokens produce the cleanest output. For huge dashboard
开发者
Expo Router vs React Navigation: Which One Should You Use in 2026?
If you've spent any time building React Native apps, you've already bumped into the question. You're setting up a new project, you need to move users between screens, and suddenly you're 40 minutes deep in a documentation rabbit hole wondering whether to go with the familiar React Navigation setup or take the leap to Expo Router. This article is going to break it all down, no hype, no fanboy energy, just an honest look at both options so you can make the call that actually fits your project. First, What Does "Routing" Even Mean in a Mobile App? On the web, routing is pretty intuitive. You type a URL, the browser goes to a page. Simple. In mobile apps, there's no URL bar, no browser history button, nothing like that. But users still need to move between screens, go back to where they came from, open modals, tab between sections, and all of that has to feel smooth and natural. So in mobile development, routing is basically the system you use to manage how screens stack on top of each other, how state is preserved when you go back, how deep links work, and how the app knows which screen to show based on where the user is in the flow. Think of it like this: routing is "moving between screens while keeping your app's memory intact." When someone logs in, fills out a form, gets distracted and opens a modal, then comes back, the app should remember all of that. Routing is the machinery underneath that makes it happen. In React Native, this doesn't come out of the box. The framework gives you the building blocks, but you have to wire up the navigation yourself. That's where libraries come in. Why Navigation Is Such a Big Deal in React Native React Native apps are essentially single-page applications. Everything runs in one JavaScript thread, rendered to native views. There's no browser doing the heavy lifting of managing history or transitions. You're responsible for it all. Bad navigation kills good apps. A janky transition, a broken back button, a modal that doesn't dismi
AI 资讯
I Spent 2 Months Building a 150+ Tool Website with $0 Server Cost
📚 This is Part 1 (Opening) of the UtlKit Tech Series — Next: [Architecture & Trade-offs →] As a frontend developer, I've used countless online tools. And almost all of them suck: Sign-up required — just to format a JSON string? Ad overload — the actual tool gets squeezed into a corner Privacy concerns — your JSON might contain API keys, and the tool sends it to a server Fragmented — formatters on one site, Base64 on another, hashing on a third So I decided to build one that doesn't: no sign-up, no ads, pure client-side computation, data never leaves the browser. The goal was simple — if I need this tool, someone else does too. The result is utlkit.com : 150+ tools, 8 categories, zero server costs. Requirements Requirement Meaning Pure client-side All logic runs in the browser Zero server cost Static hosting, no Node.js backend 150+ pages One page per tool, SEO-friendly Bilingual (EN/ZH) i18n support Dark/Light mode User preference Mobile responsive Works on all devices Why Not Other Frameworks? Option Pros Cons Verdict Vanilla HTML/JS Simple Managing 150+ pages is painful Too slow VuePress / VitePress Fast Docs-oriented, not for interactive tools Not flexible enough Nuxt SSR Powerful Needs a server Violates zero-cost principle Next.js 15 + output: 'export' SSR SEO + client interactivity + static hosting Has pitfalls (covered later) ✅ Best balance The Key Decision: output: 'export' // next.config.js const nextConfig = { output : ' export ' , // Static export trailingSlash : true , // Required for static files images : { unoptimized : true }, // No image optimization server } This means: ✅ Build output is plain HTML/CSS/JS files ✅ Deployable to any static host (Cloudflare Pages, Vercel, GitHub Pages) ✅ Zero server cost ❌ No API Routes, no Server Components, limited dynamic routing Deployment: Zero Cost on Cloudflare Pages Build output : out/ directory, ~14 MB Hosting : Cloudflare Pages Domain : utlkit.com Monthly cost : $0 Build Pipeline npm run build → next build ( o
AI 资讯
From Axios to alova: how we cut 80 lines to 5
Frontend request code often involves repetitive state management. This article compares Axios and alova through a paginated list example, analyzing how request strategization reduces boilerplate and when it's a good fit. The Pattern: Paginated List in Two Ways A common requirement: fetch a user list with pagination. Approach 1: Axios const [ data , setData ] = useState ([]); const [ page , setPage ] = useState ( 1 ); const [ total , setTotal ] = useState ( 0 ); const [ loading , setLoading ] = useState ( false ); const [ error , setError ] = useState ( null ); const fetchUsers = async ( currentPage ) => { setLoading ( true ); setError ( null ); try { const res = await axios . get ( ' /api/users ' , { params : { page : currentPage , pageSize : 10 }, }); setData ( res . data . list ); setTotal ( res . data . total ); } catch ( e ) { setError ( e . message ); } finally { setLoading ( false ); } }; useEffect (() => { fetchUsers ( page ); }, [ page ]); This pattern appears in nearly every data-fetching component. The actual business logic — GET /api/users — occupies a single line. The rest is infrastructure: state declarations, loading toggles, error handling, and effect management. Approach 2: alova with usePagination const { data , total , loading , error , page , pageSize , nextPage , prevPage , } = usePagination ( ( page , pageSize ) => alovaInstance . Get ( ' /api/users ' , { params : { page , pageSize }, }), { page : 1 , pageSize : 10 } ); Both implementations are functionally identical. The key difference is where the state management logic lives: in the component (Axios) vs. inside the hook (alova). What Changed Component of Axios version Handled by alova loading state + toggling Managed internally by usePagination error state + try/catch Managed internally by usePagination data state + assignment Returned as reactive value page state + change handler Built-in nextPage / prevPage total state extraction Extracted from response automatically useEffect dependency tr
AI 资讯
Why your React tournament bracket breaks in Safari (and a 4 KB pure-CSS fix)
You build a tournament bracket with a popular React library. In Chrome it's perfect — neat columns, clean connector lines. Then you open it on an iPhone, or in Safari, or inside your Capacitor app… and every match is crammed into the top-left corner, stacked on top of the round headers. If you've ever shipped a bracket to iOS, you've probably seen this exact bug. Here's why it happens — and a tiny library that fixes it for good. The symptom It looks fine everywhere Chromium runs (Chrome, Edge, Android WebView) and completely broken everywhere WebKit runs: Safari (macOS and iOS) iOS WKWebView Capacitor / Cordova apps Electron-on-WebKit The matches don't just shift a little — they all render at coordinate (0,0) of the bracket, piling on top of each other and the headers. The cause: SVG <foreignObject> in WebKit Most React bracket libraries — @g-loot/react-tournament-brackets , react-tournament-bracket , and friends — render the bracket as an SVG and place each match's HTML inside a <foreignObject> positioned with x / y attributes. WebKit has a long-standing bug: it ignores x , y , and transform on <foreignObject> and positions the content relative to the top-level <svg> instead of the foreignObject's own coordinates. Every match therefore collapses to the origin. And there's no CSS escape hatch — x , y , and transform are all ignored on foreignObject in Safari, so you can't nudge the content back into place. I even tried patching a library to wrap each match in a <g transform="translate(x,y)"> instead of a nested <svg x y> ; WebKit ignores ancestor transforms for foreignObject positioning too. The SVG approach is simply a dead end on WebKit. The fix: don't use SVG at all A bracket is really just columns of cards joined by connector lines — and both are expressible in plain CSS. Here's the key insight. Put each round in a flex column where every match sits in an equal flex: 1 slot. Because each round has half the matches of the previous one, a match's slot spans exactl
AI 资讯
# Agentic AI: Architecture of Autonomous Systems
"A language model that answers questions is a tool. A language model that decides which questions to ask and then acts on the answers is something else entirely." Introduction: When Models Started Deciding For the first several years of modern NLP, the task was always the same: given input, produce output. One forward pass. One completion. Done. In 2022, a paper from Google Brain asked a different question. What if, instead of producing an answer directly, a model could reason about what information it needs, act to retrieve it, and revise its thinking based on what it found? The paper was ReAct: Synergizing Reasoning and Acting in Language Models (Yao et al., 2022). Applying it to an LLM created something qualitatively different: a model that could take real-world actions and adapt its reasoning based on what came back. A completion model is a calculator. An agent is a process: it has a goal, takes steps toward it, and updates when things go wrong. This week I went deep on the architecture behind these systems, the frameworks that define them, and what the open problems look like from a research perspective. Part 1: What Makes a System "Agentic"? The word "agent" gets used loosely in current literature. A clean definition comes from Russell and Norvig's Artificial Intelligence: A Modern Approach : An agent is anything that perceives its environment through sensors and acts upon that environment through actuators. For an LLM-based system, this is a loop: perceive an observation, reason about what to do, act via a tool call or output, observe the result, and loop again. But not every loop qualifies as agentic. Three properties distinguish genuinely agentic systems from tool-augmented chatbots: Property What It Means Goal persistence Maintains the original goal across multiple steps without re-prompting Adaptive planning Revises its approach based on intermediate results Tool autonomy Decides when and which tools to use, not just how to use one it was told to call Mos
AI 资讯
Building a Native QR/Barcode Scanner for React Native — New Architecture Ready
Most QR scanner libraries for React Native share the same problems — they're unmaintained, they don't support the New Architecture, or they pull in a full camera SDK for what is a single-feature module. I wanted something lean, production-grade, and built the right way. So I built it. This is react-native-qr-camera-pro — a QR and barcode scanner for React Native built entirely with native code. No JavaScript frame processing. No unnecessary dependencies. Swift on iOS, Kotlin on Android, TurboModules and Fabric throughout. Why Native-Only? The common alternative is running frame analysis in JavaScript — grabbing frames via a JS-accessible camera API and running a WASM or JS barcode decoder on them. It works, but it puts real pressure on the JS thread and limits your frame rate. With native-only processing: iOS uses AVCaptureMetadataOutput — Apple's own pipeline for detecting machine-readable codes. Frames are never copied to user space; the kernel hands off a reference to the same buffer. Android uses CameraX ImageAnalysis + ML Kit — Google's on-device barcode scanner backed by hardware-accelerated inference where available. The JS bridge is touched at most once every 500ms to deliver a result. Everything else stays native. Architecture The module is three layers: Architecture The module is three layers, each with a single responsibility: Layer What it does JavaScript / TypeScript Public API — QrCameraProView , startScanning() , stopScanning() , toggleTorch() , useBarcodeScanner() , useCameraError() Native Bridge (TurboModules + Fabric) Type-safe JSI communication between JS and native. Codegen spec drives both the iOS C++ adapter and the Android Kotlin stub. Native Platform (iOS + Android) All camera and barcode logic. AVFoundation on iOS, CameraX + ML Kit on Android. Zero JS involvement in frame processing. iOS (Swift) Class Responsibility QrCameraProSwift Owns the AVCaptureSession lifecycle BarcodeThrottler Throttle + dedup logic BarcodeTypeMapper Maps AVMetadataO
AI 资讯
The Simplest Way I Found to Build Drag and Drop in React and Next.js
My Experience Using dnd-kit in React and Next.js For a long time, I avoided building drag-and-drop features in frontend projects 😅 Not because I did not need them. Mostly because drag and drop always felt unnecessarily complicated. When you think about implementing it, your brain immediately jumps to: animations sorting logic touch support accessibility performance state synchronization and suddenly a simple UI interaction feels like a massive feature. But recently, in one of my React and Next.js projects, I decided to finally try dnd-kit. Honestly, it changed my perspective completely. I used AI to help me with the initial setup and understanding some concepts like sortable contexts and drag events, but after that, working with the library felt surprisingly smooth. And that's what impressed me most. dnd-kit feels lightweight, modern, and flexible without becoming overwhelming. It gives you the tools you need without forcing a huge architecture or complicated patterns on your app. Things I Personally Liked About dnd-kit Very clean React-first API Lightweight and composable Works really well in React and Next.js projects Building sortable lists feels much simpler than expected Flexible enough for custom UI and interactions Good developer experience overall Something Interesting I Noticed When a library has a clean architecture and predictable patterns, AI becomes much more useful while learning it. The generated examples were easier to understand, easier to debug, and easier to customize compared to many older drag-and-drop solutions. If you are building things like: kanban boards sortable lists draggable cards dashboards reorderable tables I definitely recommend taking a look at dnd-kit. It ended up being much simpler and more enjoyable than I expected. Website https://dndkit.com/
AI 资讯
Advanced Hooks & State Management Patterns in React
Read Time: ~14 minutes | Building on React fundamentals to master state management at scale Prerequisites : Familiarity with React basics, useState, useEffect (Part 1) 🔗 Series Navigation ← Part 1: Complete Guide from Zero to Production Part 2: Advanced Hooks & State Management ← YOU ARE HERE → Part 3: Performance Optimization (coming next) 📌 What You'll Learn By the end of this guide, you'll understand: ✅ Creating powerful custom hooks ✅ When and how to use useReducer ✅ Managing state globally with Context API ✅ Redux fundamentals and when to use it ✅ Modern alternatives: Zustand and Jotai ✅ Choosing the right pattern for your project ✅ Real-world shopping cart implementation 🎣 Custom Hooks: Reusing Logic Across Components Custom hooks are regular JavaScript functions that let you extract component logic into reusable functions. They're one of the most powerful React patterns. Rule #1: Custom Hooks Must Start with "use" // ✅ Correct - starts with "use" function useFormInput ( initialValue ) { const [ value , setValue ] = useState ( initialValue ); return { value , bind : { value , onChange : e => setValue ( e . target . value ) }, reset : () => setValue ( initialValue ) }; } // ❌ Wrong - doesn't start with "use" function formInput ( initialValue ) { ... } Example #1: useFormInput Hook import { useState } from ' react ' ; function useFormInput ( initialValue = '' ) { const [ value , setValue ] = useState ( initialValue ); return { value , setValue , bind : { value , onChange : e => setValue ( e . target . value ) }, reset : () => setValue ( initialValue ) }; } // Using the custom hook function LoginForm () { const email = useFormInput ( '' ); const password = useFormInput ( '' ); const handleSubmit = ( e ) => { e . preventDefault (); console . log ( email . value , password . value ); email . reset (); password . reset (); }; return ( < form onSubmit = { handleSubmit } > < input {... email . bind } placeholder = " Email " type = " email " /> < input {... password .
AI 资讯
Frontend Engineering in 2026: Mastering Performance and DX
The Redefinition of "Frontend Engineer" in 2026 The era of the frontend engineer as a purely visual specialist is over. In 2026, companies like Vercel, Linear, Figma, Shopify, and major FAANG divisions expect their frontend engineers to think in terms of systems, not just components. A modern frontend engineer must understand rendering pipelines, browser internals, network optimization, and component architecture at the same depth that a backend engineer understands database indexing or API design. This shift is reflected directly in how companies interview frontend candidates. If you walk into a 2026 frontend interview expecting to answer "what's the difference between let and const ," you will be humbled. This guide covers everything you need to know to pass a senior-level frontend interview at a top tech company. Core Web Vitals: The Mandatory Topic You Can't Skip Google's Core Web Vitals have become a standard lens through which senior frontend engineers are evaluated. Interviewers now routinely ask candidates to diagnose performance bottlenecks using CWV metrics. The three primary metrics are: LCP (Largest Contentful Paint): Measures perceived load speed. Target under 2.5 seconds. Optimized via image preloading, server-side rendering, and CDN caching. INP (Interaction to Next Paint): Replaced FID in 2024. Measures responsiveness. Optimized by breaking up long tasks, using web workers, and deferring non-critical JavaScript. CLS (Cumulative Layout Shift): Measures visual stability. Prevents jarring layout shifts by pre-defining dimensions for images, iframes, and dynamic content. Be prepared to walk through a real-world scenario: "Given an LCP score of 4.2s, what is your systematic debugging and optimization approach?" This is now a standard senior frontend interview question. React 19 and the Concurrent Rendering Model React 19 introduced a fully concurrent rendering model that fundamentally changes how components behave. Key concepts interviewers probe in 2026