✅ Hoài Nhớ, Author at Th?nk And Grow https://blog.thnkandgrow.com/author/hoainho/ Let's Do It! Sat, 28 Feb 2026 05:40:55 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.4 https://d1gj38atnczo72.cloudfront.net/wp-content/uploads/2024/04/18114102/cropped-thnkandgrow-logo-32x32.jpg ✅ Hoài Nhớ, Author at Th?nk And Grow https://blog.thnkandgrow.com/author/hoainho/ 32 32 MoodTrip: lên kế hoạch du lịch theo tâm trạng, gọn gàng và thông minh https://blog.thnkandgrow.com/vi/xay-dung-moodtrip-ung-dung-du-lich-ai/ Mon, 02 Mar 2026 01:00:00 +0000 https://blog.thnkandgrow.com/?p=2695 MoodTrip giúp bạn lên kế hoạch du lịch theo tâm trạng, ngân sách và thời tiết — với phân tích thông minh để bạn đi chơi nhẹ đầu hơn.

The post MoodTrip: lên kế hoạch du lịch theo tâm trạng, gọn gàng và thông minh appeared first on Th?nk And Grow.

]]>
Có một kiểu mệt rất quen mỗi khi tôi chuẩn bị đi chơi: mệt vì… lên kế hoạch.

Không phải vì tôi ghét du lịch. Ngược lại. Tôi thích cảm giác “đi đâu đó để thở”, để đổi cảnh, để tự thưởng cho mình sau những tuần làm việc dài. Nhưng cứ đến khâu chuẩn bị là mọi thứ biến thành một bài kiểm tra sức bền: mở 20 tab Google, lướt review, so giá, canh thời tiết, cân ngân sách, rồi lại lo “mình đang bỏ sót điều gì?”.

Và thế là niềm vui bị rò rỉ dần — trước cả khi chuyến đi bắt đầu.

overview home page

Điều khiến tôi quyết định làm MoodTrip (và cũng là thứ làm tôi bất ngờ nhất) là một câu hỏi rất đơn giản: nếu việc lên kế hoạch có thể bắt đầu từ cảm xúc thì sao?

Thay vì hỏi “bạn muốn đi đâu?”, MoodTrip hỏi: “hôm nay bạn đang muốn thư giãn, hay khám phá, hay phiêu lưu?” Rồi từ đó, AI giúp bạn ghép những mảnh rời rạc thành một hành trình có nhịp điệu.

Thách Thức (The Challenge)

Du lịch thời nay không thiếu thông tin — thứ thiếu là sự rõ ràng.

Thông tin nằm rải rác ở mọi nơi: bài review dài, video ngắn, hội nhóm, bản đồ, thời tiết, chi phí, lịch mở cửa. Mỗi nguồn lại nói một kiểu. Càng đọc, bạn càng hoang mang. Và cuối cùng, bạn chọn bừa — hoặc chọn theo quán tính.

Tôi từng nghĩ “vậy thì phải chịu thôi”. Nhưng rồi tôi nhận ra: đây là một kiểu thách thức rất… thnkandgrow.

Thách thức không chỉ để than thở. Nó là lời mời để mình học một điều mới: cách biến hỗn độn thành một kế hoạch tử tế, và cách dùng công nghệ để phục vụ những khoảnh khắc đời thường.

MoodTrip ra đời từ nhu cầu đó — không phải để “thay thế” trải nghiệm du lịch, mà để giảm bớt phần công việc lặp lại, giúp bạn giữ được năng lượng cho điều quan trọng: tận hưởng.

Hành Trình (The Journey)

Tôi muốn MoodTrip có cảm giác giống như một người bạn đồng hành hơn là một biểu mẫu.

Bạn mở ứng dụng lên, thấy một khung cảnh thiên nhiên êm dịu. Nó không cố gắng gây ấn tượng bằng chữ nghĩa. Nó chỉ nhắc bạn rằng: mục tiêu của chuyến đi là để sống chậm lại, hoặc để sống hết mình — tùy bạn.

1) Bắt đầu từ tâm trạng

MoodTrip có 6 lựa chọn tâm trạng:

  • Thư giãn — dành cho những ngày bạn muốn thở sâu và nghỉ ngơi
  • Khám phá — dành cho người thích đi nhiều nơi, thử nhiều thứ
  • Thiên nhiên — dành cho rừng, biển, núi và những buổi sáng có sương
  • Lãng mạn — dành cho các khoảnh khắc chậm, đẹp và có “chất thơ”
  • Phiêu lưu — dành cho hoạt động ngoài trời, vận động, trải nghiệm mới
  • Văn hóa — dành cho bảo tàng, di sản, ẩm thực địa phương, câu chuyện vùng đất

Bạn không cần biết mình muốn đi đâu ngay lập tức. Bạn chỉ cần biết mình muốn cảm thấy thế nào.

2) Chọn điểm đến và ngày khởi hành

Ở phiên bản V2, MoodTrip hỗ trợ điểm đến toàn cầu. Dù bạn muốn một cuối tuần ở Đà Lạt, hay một chuyến dài ngày tới Tokyo, MoodTrip vẫn bắt đầu theo cùng một logic: đặt cảm xúc làm trung tâm, rồi mới đặt lịch trình.

Việc chọn ngày khởi hành nghe có vẻ nhỏ, nhưng nó thay đổi chất lượng kế hoạch. Vì thời tiết của “tháng 5” khác rất nhiều với thời tiết của “ngày 12/5”. Khi bạn có ngày cụ thể, gợi ý về hành trình, đồ mang theo, và những lưu ý an toàn cũng thực tế hơn.

3) Ngân sách không còn là nỗi lo mơ hồ

Tôi ghét cảm giác “không biết chuyến này tốn bao nhiêu”. MoodTrip biến điều đó thành một thao tác đơn giản: kéo thanh ngân sách từ 500.000 VND đến 20.000.000 VND.

Rồi AI sẽ bám theo giới hạn đó để gợi ý:

  • Ăn ở mức nào thì hợp
  • Ở đâu để vừa ổn vừa đáng
  • Di chuyển thế nào để không bị đội chi phí

Quan trọng hơn: bạn được nhìn thấy bản tóm tắt ngân sách rõ ràng. Không phải để bóp nghẹt niềm vui, mà để bạn tự tin tận hưởng mà không phải “căng thẳng âm thầm”.

4) AI tạo lịch trình theo ngày — nhanh nhưng vẫn có chiều sâu

Chỉ sau vài giây, MoodTrip đưa ra lịch trình theo ngày với các gợi ý về:

  • Điểm tham quan (theo nhịp độ phù hợp với tâm trạng)
  • Gợi ý quán ăn
  • Gợi ý chỗ ở
  • Ước tính chi phí
  • Link Google Maps để bạn mở đường đi ngay
planing

Điều tôi thích nhất không phải là “nhanh”. Mà là cảm giác: “À, vậy là chuyến đi này có hình hài rồi.”

Một kế hoạch tốt không nhất thiết phải hoàn hảo. Nó chỉ cần đủ rõ để bạn bắt đầu.

5) Thời tiết và gợi ý đồ mang theo

Một kế hoạch du lịch mà không quan tâm thời tiết thì giống như mang ô… vào ngày nắng.

MoodTrip hiển thị dự báo thời tiết và đưa ra gợi ý đồ mang theo theo kiểu rất đời thường:

  • Nếu mưa: áo khoác nhẹ, áo mưa, túi chống nước
  • Nếu nắng gắt: kem chống nắng, mũ, kính, nước
  • Nếu lạnh: áo ấm, khăn, miếng dán giữ nhiệt

Bạn không còn phải tự tra, tự đoán, tự tưởng tượng.

6) Cảnh báo kẹt xe và lưu ý an toàn

Đây là phần khiến tôi thấy MoodTrip “có trách nhiệm”. Du lịch không chỉ là check-in. Nó còn là việc tránh rủi ro không đáng có.

Ứng dụng có thể nhắc bạn về:

  • Khu vực dễ kẹt xe
  • Sự kiện, lễ hội làm thay đổi mật độ người/xe
  • Một vài lưu ý an toàn cơ bản theo bối cảnh

Không phải để dọa. Mà để bạn chủ động.

7) AI Chat Companion — hỏi ngay khi bạn đang phân vân

Khi đã có lịch trình, câu hỏi mới bắt đầu xuất hiện:

  • “Có quán ăn nào gần chỗ mình đang ở không?”
  • “Mình có thể đổi thứ tự ngày 2 và ngày 3 được không?”
  • “Nếu mình muốn nhẹ nhàng hơn thì nên bỏ bớt điểm nào?”

MoodTrip có một nút chat nổi như một người bạn đi cạnh. Bạn hỏi, AI trả lời theo đúng kế hoạch và bối cảnh của bạn — để bạn điều chỉnh nhanh mà không phải quay lại từ đầu.

8) Lưu lại, xuất PDF, và dùng như một ứng dụng trên điện thoại

Một chuyến đi tốt thường được chuẩn bị trước và được xem lại trong lúc đi.

Vì vậy MoodTrip hỗ trợ:

  • Lưu lịch trình để xem lại sau
  • Xuất PDF để bạn tải về, đọc offline, hoặc gửi cho bạn đồng hành
  • Cài đặt như ứng dụng trên điện thoại (PWA) để mở nhanh như app, tiện khi đang di chuyển
Mobile app

Với tôi, đây là điểm “thực dụng” nhất: trong những khoảnh khắc đang đi ngoài đường, bạn cần thứ gì đó chạy nhanh, dễ xem, không rườm rà.

Những Điều Rút Ra (Key Takeaways)

Làm MoodTrip khiến tôi rút ra vài điều không chỉ liên quan tới sản phẩm, mà liên quan tới cách mình sống và lựa chọn.

1) Công nghệ nên phục vụ cảm xúc, không phải ngược lại

Rất nhiều công cụ bắt bạn phải “đúng” ngay từ đầu: đúng điểm đến, đúng lịch, đúng danh sách. MoodTrip đi theo hướng khác: bắt đầu từ câu hỏi mềm hơn — “bạn muốn cảm thấy gì?”.

Khi bắt đầu từ cảm xúc, kế hoạch trở nên nhân văn hơn. Và bạn cũng dễ trung thực hơn với chính mình.

2) AI mạnh nhất khi hiểu bối cảnh

AI không chỉ là “trả lời câu hỏi”. Nó hữu ích nhất khi được đặt trong bối cảnh đủ rõ:

  • Tâm trạng
  • Ngân sách
  • Ngày khởi hành
  • Điểm đến
  • Thời tiết

Khi đó, gợi ý không còn chung chung. Nó trở thành một kế hoạch có thể dùng được.

3) Công cụ tốt là công cụ bạn sẽ dùng thật

Một ứng dụng tuyệt vời trên lý thuyết nhưng khó dùng ngoài đời thì vẫn là… khó dùng.

Tôi học cách thiết kế mọi thứ theo hướng đơn giản, nhanh, và “mở ra là làm được ngay”. Vì du lịch là lúc bạn không muốn học thêm một thứ phức tạp.

4) Lên kế hoạch nên là một phần của niềm vui

Nếu lên kế hoạch làm bạn kiệt sức, bạn sẽ mang sự kiệt sức đó vào chuyến đi.

Tôi muốn MoodTrip biến phần chuẩn bị thành một trải nghiệm nhẹ nhàng: chọn tâm trạng, chọn ngày, đặt ngân sách, rồi để AI lo phần còn lại. Bạn giữ năng lượng cho những điều đáng nhớ.

Tương Lai Phía Trước (Future Vision)

MoodTrip V2 mới chỉ là bước đầu. Tôi nghĩ một trợ lý du lịch theo tâm trạng còn có thể đi xa hơn, theo vài hướng rất thú vị:

  • Hỗ trợ đa ngôn ngữ (English, Japanese, Korean) để bạn và bạn bè ở nhiều nơi cùng dùng
  • Lập kế hoạch nhóm: đồng bộ lịch trình với bạn đồng hành, ai cũng thấy cùng một phiên bản
  • Tích hợp đặt dịch vụ theo thời gian thực: khách sạn, vé, trải nghiệm — để “kế hoạch” tiến một bước gần hơn tới “thực hiện”
  • Chia sẻ và khám phá: bạn có thể chia sẻ lịch trình, hoặc tìm cảm hứng từ hành trình của người khác
  • Đi đường bằng AR: mở camera và được gợi ý hướng đi/điểm thú vị xung quanh
  • Cộng đồng đánh giá: người dùng phản hồi để AI ngày càng hiểu điều gì là “đáng”
  • Trợ lý giọng nói: lên kế hoạch bằng cách trò chuyện tự nhiên, nhất là khi đang bận tay

Tôi không hứa MoodTrip sẽ thay thế cảm giác tự khám phá. Tôi chỉ hứa một điều: MoodTrip sẽ tiếp tục tiến về phía giảm bớt lo lắng, tăng thêm tự do cho người thích đi.

Câu Hỏi Suy Ngẫm (Reflection Questions)

1) Bạn thường bắt đầu lên kế hoạch du lịch từ đâu — từ điểm đến hay từ cảm xúc?

2) Lần cuối bạn để AI giúp một quyết định cá nhân là khi nào? Kết quả có làm bạn ngạc nhiên không?

3) Nếu có thể đi bất cứ đâu ngay bây giờ với tâm trạng hiện tại, bạn sẽ chọn đâu?

4) Với bạn, “một chuyến đi đáng” là chuyến đi có gì: ít lịch trình hay nhiều trải nghiệm?

Lời mời nhỏ

Nếu bạn muốn thử một cách lên kế hoạch mới — bắt đầu từ tâm trạng, rồi để AI gợi ý hành trình — bạn có thể trải nghiệm MoodTrip tại đây:

Moodtrip – Hãy để cảm súc dẫn đường

Nếu bạn dùng thử, tôi rất muốn nghe bạn kể: bạn chọn tâm trạng nào, và AI đã gợi ý một chuyến đi ra sao?

The post MoodTrip: lên kế hoạch du lịch theo tâm trạng, gọn gàng và thông minh appeared first on Th?nk And Grow.

]]>
DevLens: Catch Every Silent Failure in Your JavaScript App https://blog.thnkandgrow.com/devlens-catch-every-silent-failure-in-your-javascript-app/ Fri, 27 Feb 2026 09:37:17 +0000 https://blog.thnkandgrow.com/?p=2686 Stop adding console.log everywhere. DevLens auto-detects API failures, null access, and missing render data in your JavaScript app — with zero config

The post DevLens: Catch Every Silent Failure in Your JavaScript App appeared first on Th?nk And Grow.

]]>
The 30-Minute Debugging Session That Shouldn’t Exist

You’ve been here. Your app renders a blank page. You open the console — nothing. No red text, no stack trace, no clue. So you start the ritual: add console.log before the fetch call. Refresh. Add another one after the response. Refresh. Sprinkle a few more inside the component. Refresh, refresh, refresh.

Twenty minutes later, you find it. The API returned a 500, but your code didn’t check the status. The response body was empty. user.profile.settings is undefined. The component tried to render settings.theme and got… nothing. No crash. No error. Just a blank white screen staring back at you.

This isn’t a rare edge case. This is Tuesday.

The root of the problem is that JavaScript is designed to fail silently. Accessing a property on undefined returns undefined — it doesn’t throw. A fetch call that gets a 500 response doesn’t reject the promise. Your component receives null from a hook and renders nothing. The language actively helps your bugs hide.

What If Your App Could Tell You?

That’s the idea behind DevLens. It’s an open-source SDK that watches your running JavaScript app and automatically detects the silent failures that waste your time — API errors, null access, missing render data, unhandled rejections — then logs them with enough context to fix the issue immediately.

DevLens is a development-time tool. It runs in your browser while you’re coding. It’s not Sentry. It’s not Datadog. Those are production monitoring tools that tell you what happened after users hit the bug. DevLens tells you while you’re looking at the screen, before you even notice something is wrong.

Think of it as ESLint for runtime errors — but instead of scanning your source code, it watches your running app.

Zero config. Dev-only. Drop it in and see everything.

What It Catches

Network Failures

DevLens automatically intercepts every fetch and XMLHttpRequest call in your app. When an API returns a 4xx or 5xx status, you see this in your console:

[NET] DevLens [ERROR] network: POST /api/users returned 500 Internal Server Error
  |- Status: 500
  |- Duration: 1234ms
  |- Suggestion: Server returned 500 - check server logs
  \- Source: NetworkInterceptor

No manual try/catch. No response status checking. You just see it.

Structured console output with severity levels, property paths, and actionable suggestions

Structured console output with severity levels, property paths, and actionable suggestions

Null and Undefined Access

This is the big one. DevLens wraps your data objects in an ES6 Proxy that tracks every property access. When you hit null or undefined, it tells you the exact path:

import { useGuardedState } from '@devlens/react';

function UserProfile() {
  const [user, setUser] = useGuardedState(initialUser, 'UserProfile');

  // If user.profile.avatar is null, DevLens logs:
  // [NULL] DevLens [WARN] null-access: Property "avatar" is null
  //   at path "user.profile.avatar"
  return <img src={user.profile.avatar} />;
}

Instead of a blank <img> tag and a confused developer, you get the property name, the full path, the actual value found, and a suggestion. Before it cascades into a visible bug.

Missing Render Data

Sometimes the data isn’t null on a deeply nested path — it’s null at the top level. A hook returns undefined. A prop is missing. DevLens watches for that too:

import { useGuardedEffect } from '@devlens/react';

function Dashboard({ user, posts, settings }) {
  useGuardedEffect({ user, posts, settings }, 'Dashboard');

  // If posts is undefined:
  // [RENDER] DevLens [WARN] render-data: "posts" is undefined in Dashboard
  return <div>...</div>;
}

One line. All your critical data values monitored.

Unhandled Errors

Global window.onerror and unhandled promise rejections are caught and logged with full stack traces and suggestions. You stop missing the errors that fire once during initial load and scroll off the top of your console.

Error Boundary (React)

DevLens includes an enhanced React Error Boundary that integrates with the detection engine:

<DevLensErrorBoundary
  fallback={(error, reset) => (
    <div>
      <p>Error: {error.message}</p>
      <button onClick={reset}>Retry</button>
    </div>
  )}
  onError={(error) => trackError(error)}
>
  <RiskyComponent />
</DevLensErrorBoundary>

When a component tree crashes, the error is captured by DevLens with context — not just the error message, but what the component was rendering and what data it had.

Under the Hood

A few technical details for the curious.

Network Interceptor works by monkey-patching window.fetch and XMLHttpRequest.prototype.open/send. It records the URL, method, status, response time, and body. When you call uninstall(), the original implementations are restored cleanly. It never touches your request or response data — it only observes.

Data Guardian uses ES6 Proxy with recursive wrapping. When you call guardian.guard(obj, 'label'), it returns a Proxy that intercepts get operations. Each nested access extends the tracked path — so accessing user.profile.avatar builds the path "user" -> "user.profile" -> "user.profile.avatar". When the value at any step is null or undefined, DevLens reports it with the full path. A maxDepth setting (default: 5) prevents infinite recursion on circular references.

The UI Panel is rendered inside a Shadow DOM container. This means its CSS — all 900+ lines of it — is completely isolated from your app. Your Tailwind classes won’t break the panel. The panel’s styles won’t leak into your layout. It sits at z-index: 2147483647 so it always floats above everything.

Production Safety is built in at every level. When NODE_ENV === 'production', the engine returns no-op implementations. The DevLensProvider renders its children directly with zero overhead. sideEffects: false in every package.json ensures your bundler tree-shakes the entire library out of production builds. No data is ever sent anywhere — everything stays in your browser.

Quick Start

React

npm install @devlens/core @devlens/react
import { DevLensProvider, DevLensErrorBoundary } from '@devlens/react';

function App() {
  return (
    <DevLensProvider>
      <DevLensErrorBoundary>
        <YourApp />
      </DevLensErrorBoundary>
    </DevLensProvider>
  );
}

That’s it. Open your browser console.

Vue 3

npm install @devlens/core @devlens/vue
import { createApp } from 'vue';
import { createDevLensPlugin } from '@devlens/vue';

const app = createApp(App);
app.use(createDevLensPlugin());
app.mount('#app');

Vanilla JS

npm install @devlens/core
import {
  createDetectionEngine,
  createNetworkInterceptor,
  createGlobalCatcher,
  createDataGuardian,
} from '@devlens/core';

const engine = createDetectionEngine();

const network = createNetworkInterceptor(engine);
network.install();

const catcher = createGlobalCatcher(engine);
catcher.install();

const guardian = createDataGuardian(engine);
const data = guardian.guard(apiResponse, 'apiResponse');

// Accessing null/undefined properties now auto-logs
console.log(data.user.profile.avatar);

Works with React, Vue, Svelte, vanilla JS, or anything that runs in a browser.

The Visual Tools

Console logging is the starting point, but DevLens goes further.

Floating Debug Panel

Add @devlens/ui and you get a floating panel overlay in your browser — toggle it with Ctrl+Shift+D.

import { createDetectionEngine } from '@devlens/core';
import { createDevLensPanel, createPanelReporter } from '@devlens/ui';

const panel = createDevLensPanel({ theme: 'dark' });
const engine = createDetectionEngine({
  reporter: createPanelReporter(panel),
});

The panel gives you:

  • Issue list with severity bars (red/amber/blue) and category badges
  • Timeline view showing issues chronologically
  • Severity and category filtering — show only errors, or only network issues
  • Full-text search across all issue messages, paths, and sources
  • Session persistence — issues survive page reloads
  • JSON/CSV export — download your issue log for sharing or analysis

All rendered inside Shadow DOM. Your app’s styles can’t break it. Its styles can’t break your app.

debug panel overlay


The floating debug panel overlay — always accessible via Ctrl+Shift+D, never interferes with your app.

Dashboard

For deeper investigation, DevLens includes a full dashboard that opens in a separate browser window.

The DevLens Dashboard


The DevLens Dashboard showing detected issues with severity indicators, category badges, and expandable detail rows.

It features four tabs:

Issues — A detailed list of every detected issue. Click any row to expand and see the property path, actual value found, source component, suggestion, and stack trace. Each issue has an inline “Analyze with AI” button.

Timeline — Chronological view with severity-colored dots on a vertical timeline. Good for understanding the sequence of failures.

AI Analysis — Select a model (Gemini, Claude, or GPT) and analyze all your detected issues at once. The AI identifies root causes, detects patterns across multiple issues, and suggests specific code fixes.

Settings — Session configuration, connection status, and export options.

AI-powered analysis identifies root causes, detects patterns, and suggests fixes.

Timeline view showing issues chronologically with severity-colored dots.

Timeline view showing issues chronologically with severity-colored dots.

Vite Plugin

If you’re using Vite, you can embed the dashboard directly into your dev server:

npm install @devlens/vite
// vite.config.ts
import devlens from '@devlens/vite';

export default {
  plugins: [devlens()],
};

The dashboard is now available at http://localhost:5173/__devlens__/. No extra terminal window. No extra command. It’s served by the same dev server you’re already running.

What’s Next

DevLens is currently at v2.1. Here’s what’s shipped and what’s coming:

VersionWhatStatus
v1.0Console logging — network, null detection, error boundariesShipped
v2.0UI panel overlay, Vue 3 supportShipped
v2.1Inspector window, embedded dashboard via Vite pluginCurrent
v3.0Deep AI integration — real-time pattern detection, auto-fix generation, CI/CD integrationIn planning

The v3.0 release will analyze patterns across your detected issues over time, identify recurring root causes, and generate code fixes — directly in your dev console or dashboard. Think of it as a debugging co-pilot that learns your app’s failure patterns.

The Numbers

  • ~20KB core engine, ~5KB per framework adapter
  • Zero runtime dependencies in @devlens/core
  • Dual ESM + CJS output with full TypeScript declarations
  • Supports React 17+, Vue 3.3+, and vanilla JS
  • MIT licensed. Fully open source.

Try It

npm install @devlens/core @devlens/react

Five lines of code. Every silent failure in your app, caught and explained.

If DevLens saves you one 30-minute debugging session, it’s already paid for itself. And it will save you a lot more than one.

The post DevLens: Catch Every Silent Failure in Your JavaScript App appeared first on Th?nk And Grow.

]]>
React Debugger Extension: Detect Re-renders, Memory Leaks, and Anti-patterns in Real Time https://blog.thnkandgrow.com/react-debugger-extension/ Sun, 15 Feb 2026 03:43:25 +0000 https://blog.thnkandgrow.com/?p=2682 Stop Debugging React Blindly: Meet React Debugger Extension A powerful Chrome DevTools extension that makes debugging React applications feel less like guesswork and more like detective work. The Problem Every React Developer Faces We’ve all been there. Your React app is slow. Components re-render for no apparent reason. Memory usage keeps climbing. Layout shifts ruin […]

The post React Debugger Extension: Detect Re-renders, Memory Leaks, and Anti-patterns in Real Time appeared first on Th?nk And Grow.

]]>
Stop Debugging React Blindly: Meet React Debugger Extension

A powerful Chrome DevTools extension that makes debugging React applications feel less like guesswork and more like detective work.


The Problem Every React Developer Faces

We’ve all been there. Your React app is slow. Components re-render for no apparent reason. Memory usage keeps climbing. Layout shifts ruin the user experience. And you’re left wondering: where do I even start?

Traditional debugging tools help, but they weren’t built with React’s unique challenges in mind. That’s why I built React Debugger Extension — a Chrome DevTools extension specifically designed to surface the issues that matter most in React applications.


What Makes This Different?

Unlike generic performance tools, React Debugger understands React’s mental model. It hooks directly into React’s fiber architecture to give you insights that are actually actionable.

UI & State Issues Detection

Catch anti-patterns before they become bugs:

  • Direct state mutation — The silent killer of React apps
  • Missing keys — That console warning you’ve been ignoring
  • Index as key — Works until it spectacularly doesn’t
  • Duplicate keys — When your list goes haywire

Performance Analysis

See exactly what’s slowing you down:

  • Component render statistics with timing data
  • Top re-rendering components — Find the culprits instantly
  • Render triggers (props, state, context, parent) — Know why it rendered
  • React Scan visualization — See re-renders directly on the page with color-coded overlays

Side Effects Monitoring

useEffect issues are notoriously hard to debug. Not anymore:

  • Missing cleanup detection
  • Dependency array problems
  • Infinite loop risks
  • Stale closure warnings

CLS (Cumulative Layout Shift) Tracking

Layout shifts destroy UX. Track them in real-time:

  • Live CLS score monitoring
  • Top shift contributors identified by element
  • Timeline of shift events

Redux DevTools Built-In

No need for separate extensions:

  • State tree browser with search
  • Action history
  • Dispatch custom actions for testing

Memory Monitoring

Catch memory leaks before your users do:

  • Heap usage tracking
  • Growth rate analysis
  • Crash log with stack traces

Timeline View

See everything in chronological order:

  • Renders, state changes, effects, errors — all correlated
  • Filter by event type
  • Search for specific components
  • Capture snapshots for comparison

Installation

Option 1: One Command (Recommended)

npx @nhonh/react-debugger

Then load it in Chrome:

  1. Go to chrome://extensions/
  2. Enable Developer mode
  3. Click Load unpacked
  4. Select the downloaded folder

That’s it. Open DevTools (F12) and find the “React Debugger” tab.

Option 2: From Source

git clone https://github.com/hoainho/react-debugger-extension.git
cd react-debugger-extension
npm install
npm run build

Load the dist folder in Chrome as above.


See It In Action

Catching Index-as-Key Issues

// This common mistake gets flagged immediately
{items.map((item, index) => (
  <li key={index}>{item}</li>
))}

Open the UI & State tab, see the warning, and fix it before it causes bugs.

Finding Excessive Re-renders

Enable React Scan in the Performance tab. Components flash with colors:

  • Green = 1 render (good)
  • Yellow = 2-3 renders (watch it)
  • Red = 10+ renders (investigate now)

Detecting Missing Cleanup

useEffect(() => {
  const id = setInterval(() => console.log("tick"), 1000);
  // Missing cleanup = memory leak
}, []);

The Side Effects tab catches this instantly and tells you exactly what’s wrong.


Built for Developers at Every Level

Juniors

Start with the UI & State and Side Effects tabs. Learn React patterns by seeing what NOT to do — with actionable suggestions for every issue.

Mid-Level

Focus on the Performance and Timeline tabs. Understand render cascades. Apply React.memo, useMemo, useCallback where they actually matter.

Seniors

Use all tabs for a holistic view. Correlate Redux actions with render storms. Monitor memory patterns over time. Optimize CLS for better Core Web Vitals scores.


Why I Built This

After years of debugging React applications, I got tired of the same cycle:

  1. User reports slowness
  2. Open React DevTools Profiler
  3. Stare at flame graphs
  4. Make educated guesses
  5. Repeat until something works

React Debugger cuts through the noise. It tells you:

  • What is wrong
  • Where it’s happening
  • Why it’s a problem
  • How to fix it

Links


Open Source & MIT Licensed

This is a community tool. Contributions are welcome — whether it’s bug reports, feature requests, or pull requests.

Give it a try. Break your bad React habits. Ship faster, more reliable applications.

Your React apps deserve better debugging. 🚀


Built with ❤ by NhoNH

React Debugger Extension: Detect Re-renders, Memory Leaks, and Anti-patterns in Real Time

The post React Debugger Extension: Detect Re-renders, Memory Leaks, and Anti-patterns in Real Time appeared first on Th?nk And Grow.

]]>
Từ Bế Tắc Debugging Đến Kiểm Soát Hoàn Toàn: Hành Trình Xây Dựng React Debugger Extension https://blog.thnkandgrow.com/vi/hanh-trinh-xay-dung-react-debugger-extension/ Mon, 09 Feb 2026 14:57:33 +0000 https://blog.thnkandgrow.com/?p=2672 Nhật ký hậu trường: Vì sao debug React khiến tôi cạn kiệt năng lượng – và React Debugger đã kéo tôi ra khỏi vòng lặp vô tận đó Có một ngày thứ Ba tưởng như bình thường: tôi nhận một báo cáo khá mơ hồ – trang thanh toán Next.js đôi lúc trắng xóa khi […]

The post Từ Bế Tắc Debugging Đến Kiểm Soát Hoàn Toàn: Hành Trình Xây Dựng React Debugger Extension appeared first on Th?nk And Grow.

]]>

Nhật ký hậu trường: Vì sao debug React khiến tôi cạn kiệt năng lượng – và React Debugger đã kéo tôi ra khỏi vòng lặp vô tận đó

Có một ngày thứ Ba tưởng như bình thường: tôi nhận một báo cáo khá mơ hồ – trang thanh toán Next.js đôi lúc trắng xóa khi refresh. Không có stack trace, error boundary không nhúc nhích, mọi thứ “chạy” nhưng UI biến mất. Tôi lao vào đặt console.log khắp nơi, bật Profiler của React DevTools, xem Performance tab của Chrome. Sau gần hai ngày quay cuồng, tôi mới phát hiện ra thủ phạm chỉ là một đoạn JSX render Date.now(), khiến HTML phía server lệch so với client. Đồng nghiệp QA đùa rằng “phải cúng bái code” mới xong. Nhưng ở góc nhìn của tôi, đây chỉ là một vòng lặp quen thuộc – debug React không chỉ đau đầu, nó còn ăn mòn năng lượng sáng tạo.

Bài viết này không phải là một bản PR khô khan. Tôi muốn kể lại hành trình loay hoay với các “con boss” của debugging React, những lần review code dài vô tận vẫn không nhìn ra nguyên nhân, và cách mà React Debugger – một extension DevTools do chính tay tôi xây dựng – giúp tôi cắt giảm hơn 60% thời gian đuổi theo bug. Tôi sẽ đi qua những lỗi nguy hiểm tiềm ẩn, ví dụ thực tiễn, phân tích giá trị cốt lõi của extension, đào sâu từng tab và tính năng, chia sẻ best practice, khẳng định độ tin cậy, rồi kết lại bằng lời hứa cá nhân tiếp tục cải tiến để cộng đồng React không còn phải “bán linh hồn” cho việc gỡ bug.


1. Debug React chưa bao giờ “dễ thương” trong mắt tôi

Hydration mismatch – “kẻ” khiến cả app trắng xóa

Trong các dự án Next.js, việc server-render và client-render khớp nhau là tối quan trọng. Thế nhưng những khác biệt tưởng như vô hại – Math.random() trong JSX, định dạng ngày theo locale, điều kiện typeof window !== 'undefined' – lại đủ để phá hỏng cả phiên. React log thông báo lạnh lùng “Hydration failed because the initial UI does not match…” và dừng lại. Tôi đã từng tốn hơn 20 giờ chỉ để tìm một component <Hero /> gọi Date.now() ở render đầu tiên. Cảm giác như mò kim đáy bể.

useEffect dependency hell & stale closure

useEffect, useCallback, useMemo vốn là cứu tinh, nhưng dependency thiếu/thừa hoặc không ổn định sẽ sinh ra vòng lặp render vô hạn, API gọi liên tục, dữ liệu “stale” cực kỳ khó đoán. Dan Abramov đã viết cả bài dài “A Complete Guide to useEffect”, ngầm thừa nhận rằng hook này là “đầu tàu” của nhiều vấn đề. Tôi nhận ra: không chỉ biết “nên” đưa gì vào dependency, mà còn phải biết khoảnh khắc nào effect bị kích hoạt, bởi input nào – điều mà DevTools mặc định không chỉ rõ.

“Re-render hell” & referential instability

Một component rerender 200 lần vì props nhận hàm inline tạo mới, Profiler chỉ bảo “component rerender”. Còn “tại sao” thì tôi phải tự so sánh props cũ/mới, context cũ/mới. Tôi nhớ lần audit một component “ProductList” rerender liên tục do parent truyền filters={{ category: 'all' }} được tạo mới mỗi render. Giải pháp chỉ là useMemo, nhưng để chứng minh: log diff, chụp snapshot, viết lại cả “hồ sơ” render. Công việc lặt vặt, tốn thời gian.

Race condition với async state

Người dùng chuyển tab nhanh, API tab A trả lời sau B, UI hiển thị sai. Muốn tái hiện bug phải log tay, gắn timestamp, đo đạc state thủ công… Trong khi tôi cần ship tính năng mới, việc “làm sản phẩm” trở thành xa xỉ.

State sync & prop drilling

Dù React khuyến cáo “lift state up”, nhưng khi state chia sẻ qua nhiều tầng hoặc context trùm cả app, việc truy vết “ai bắn state update” giống như theo dõi dây mơ rễ má. Tôi từng commit cả trăm dòng console.log chỉ để biết giá trị selectedUser dịch chuyển ra sao qua các component. Review cuối tuần? Một chuỗi diff vô nghĩa nhưng không thể bỏ.

Memory leak & layout shift

React cộng Chrome API, WebSocket, timers… nếu thiếu cleanup, heap memory tăng đều, app giật. DevTools Memory view giúp đo snapshot nhưng khó thao tác liên tục. Layout shift (CLS) thì càng “căng”: biết có vấn đề, nhưng không biết element nào gây shift.

Những vấn đề này ngốn hàng giờ, khiến code review biến thành “địa ngục diff”, còn năng lượng sáng tạo bị đốt sạch.


2. Hai câu chuyện thực tế (và cách thời gian bay màu trong tay tôi)

Case 1: Sidebar monitoring tool

  • Triệu chứng: Sidebar React freeze.
  • Trước: 14 giờ cắm đầu. Profiler báo Sidebar render lâu, nhưng trigger mơ hồ. Tôi viết script diff props, vẫn chỉ dừng ở phỏng đoán.
  • Sau khi dùng React Debugger: Mở Timeline Tab, filter render, chụp snapshot → UserMenu rerender 62 lần, trigger “context”. Click vào chi tiết thấy UserContext đổi key “theme” vì tôi viết value={{ theme: getTheme(), user }} ngay trong render. Sửa trong 10 phút.
  • Tiết kiệm: khoảng 10 giờ (71%).

Case 2: SSR hydration bug

  • Triệu chứng: Trang blog random trắng.
  • Trước: hơn 20 giờ, tôi so HTML server-client, thêm guard, log window.
  • Sau: Dùng Timeline Tab, bật correlation giữa render & error, click snapshot → extension highlight “Hydration mismatch – component Header -> difference tại Date.now()”. Tôi fix và QA xác nhận.
  • Tiết kiệm: khoảng 12 giờ (60%).

Kể từ khi đưa React Debugger vào workflow, thời gian debug giảm rõ rệt, PR nhẹ hơn, và quan trọng nhất: tinh thần tôi đỡ bị “hành”.


3. React Debugger Extension – “máy quét MRI” do chính tôi chế tạo

Tôi xây React Debugger dưới dạng extension DevTools, xuất hiện như một tab “React Debugger”. Nó không dừng ở việc ném cảnh báo, mà tạo nên hệ quan sát đầy đủ.

  1. Observability: Mọi sự kiện render, state change, effect, error, memory, context… đều được log với timestamp, trigger, component, stack.
  2. Correlation: Khi chọn một event, extension highlight các event liên quan, tạo narrative “vì sao nó xảy ra”.
  3. Actionable remediation: Issue card nêu rõ “làm gì để sửa” (ví dụ: “missing cleanup – thêm return () => clearInterval(id);”).
  4. Realtime overlay: React Scan highlight rerender ngay trên UI.
  5. Pattern detector: Tự động flag DIRECT_STATE_MUTATION, INDEX_AS_KEY, STALE_CLOSURE, INFINITE_LOOP_RISK, v.v.

Giá trị cốt lõi (3 trụ cột tôi đặt ra)

  • Context-aware: Không chỉ hiển thị con số, extension truy vết chuỗi nguyên nhân và thành phần liên quan.
  • Time-machine: Snapshot timeline, export JSON, so sánh trước/sau refactor.
  • Full-stack view: UI, performance, side effect, memory, layout shift, Redux… hội tụ trong một giao diện.

Nguồn thông tin:

  • README mô tả tính năng: UI & State Issues, Performance Analysis, Side Effects, CLS, Redux DevTools, Timeline, Memory.
  • DEBUGGING-GUIDE.md – hướng dẫn chi tiết từng tab, metric, workflow cho cấp độ fresher/mid/senior.

4. Giải phẫu từng tab & tính năng (trong mắt người tạo ra nó)

4.1 Timeline Tab – “dòng thời gian sự kiện”

Loại eventÝ nghĩa
🔄 RenderComponent render, ghi rõ trigger: state, props, context, parent, mount
📦 State changesetState, Redux action, context update (kèm tên state/hook index)
⚡ EffectuseEffect run/cleanup với dependency preview
❌ ErrorJS error, React error boundary, stack trace
🧠 MemorySnapshot heap, growth rate, spike indicator
🔗 Context changeProvider value thay đổi, các key bị đổi

Điểm mạnh:

  • Filter theo type, search component.
  • Snapshot timeline → export JSON, so sánh sau khi tối ưu.
  • Correlation panel highlight event liên quan (render – state change – effect).
  • Render detail hiển thị diff props/state (oldValue → newValue), render reason summary, fiber depth, parent component.
  • Component path (chuỗi component từ root).
  • Batch ID: biết render nào nằm chung batch.

4.2 UI & State Tab

Tự động phát hiện bốn lỗi thường gặp:

  1. DIRECT_STATE_MUTATION
  2. MISSING_KEY
  3. INDEX_AS_KEY
  4. DUPLICATE_KEY

Mỗi issue card ghi severity, component, snippet, gợi ý fix. Điều này giúp tôi (và cả junior khi tôi review) hiểu pattern đúng.

4.3 Performance Tab

  • Statistic dashboard: số component track, tổng render, average render time (yêu cầu chế độ dev/profiler).
  • Slow renders: top component >16ms, hiển thị max/avg time, render count.
  • Top rerender: ghi rõ trigger reason (props/state/context/parent), changed keys.
  • React Scan overlay: highlight component rerender với màu:
  • xanh lá: 1×
  • vàng: 2-3×
  • cam: 4-5×
  • đỏ cam: 6-10×
  • đỏ: 10+×
  • Page load metrics: FCP, LCP, TTFB, load complete (Core Web Vitals).
  • Performance tips: checklist React.memo, useMemo, useCallback, virtualization.

4.4 Side Effects Tab

Chia issue theo nhóm:

  • Missing cleanup (leak timers, event listener, subscription).
  • Dependency issues (thiếu/thừa dependency).
  • Infinite loop risk (effect setState → rerender → effect).
  • Stale closures (callback dùng state cũ).

Issue card mô tả cụ thể, kèm snippet fix. Tab cũng liệt kê best practice (chia nhỏ effect, dùng useCallback, v.v.).

4.5 CLS Tab

  • Hiển thị current CLS score, rating (good / needs-improvement / poor) với biểu đồ (mốc 0.1, 0.25).
  • Bảng top contributor: selector, total shift, occurrences.
  • Shift timeline: 20 entry mới nhất, tô màu theo severity.
  • Tips: add width/height, aspect-ratio, reserve space, font-display.

4.6 Memory Tab

  • Monitor JS heap: used, total, limit, peak, growth rate, warning.
  • Memory bar gradient 0-100%, highlight 70/90%.
  • Trend chart: polyline used/total.
  • Crash log: JS error, promise rejection, React error, có stack, component stack, memory snapshot, analysis hint.
  • Button Start/Stop monitoring -> gửi message service worker.
  • Tips: cleanup interval, unsubscribe subscription, tránh closure giữ data lớn.

4.7 Redux Tab

  • Detect store qua window.store, window.__REDUX_STORE__, Redux DevTools, Provider context.
  • Action history (timestamp, type) + detail payload.
  • State tree browser: expand/collapse, search, edit inline giá trị (string/number/bool/null/JSON). Hỗ trợ move, delete item trong array.
  • Dispatch action: nhập type + payload JSON.
  • Setup guide khi store chưa expose (tôi đặt cuộn check list “window.store”, “window.REDUX_STORE” …).
  • Khi editing, overlay spinner, highlight “Saving…”.

4.8 Bonus: Test scenarios & tài liệu

README có sẵn test case demo (missing key, excessive render, missing cleanup, layout shift). DEBUGGING-GUIDE.md hơn 600 dòng, kể cả workflow theo cấp độ, metric threshold, keyboard shortcut, color coding.


5. Tôi đo được 60% thời gian debug tiết kiệm như thế nào?

Trong ba sprint gần đây, tôi track 12 bug cụ thể:

  • 5 bug hydration/race effect (trung bình 7 giờ → còn 2,5 giờ).
  • 4 bug rerender/perf (8 giờ → 3 giờ).
  • 3 bug UI/state (4 giờ → 1,5 giờ).

Tiết kiệm khoảng 62%. Điểm mấu chốt:

  1. Tìm root cause nhanh bằng event correlation.
  2. Giảm console.log bừa bãi, giữ PR sạch.
  3. Khi review, tôi đính kèm snapshot JSON timeline, reviewer (hoặc chính tôi một tuần sau) nhìn thấy render reason, diff state → tin tưởng fix, không cần hỏi thêm.

6. Best practice tôi đang áp dụng với React Debugger

  1. Chụp snapshot trước & sau khi tối ưu để so sánh render order, changed key.
  2. Dùng React Scan thay vì đoán: overlay highlight component rerender theo màu, không tranh luận theo cảm tính.
  3. Theo dõi Memory trong thời gian dài: start monitoring trước khi chạy stress test 10-15 phút để xem growth rate.
  4. Bookmark issue: trong UI & State tab, tôi đánh dấu, ghi chú TODO cá nhân.
  5. Kết hợp với QA: QA dùng CLS tab check layout shift, gửi log thẳng cho tôi.
  6. Workflow theo cấp độ (tôi viết trong DEBUGGING-GUIDE):
  • Fresher: tập trung UI & State + Side Effects.
  • Mid-level: Performance + Timeline + Memory.
  • Senior (hoặc chính tôi khi đóng vai tech lead): dùng tất cả, kết hợp correlation, ra quyết định kiến trúc.
  1. Expose Redux store ở dev mode: if (process.env.NODE_ENV === 'development') window.store = store; để Redux tab hoạt động tối ưu.

7. Tính minh bạch & độ tin cậy cá nhân tôi cam kết

  • Open-source MIT: Repo public, ai cũng audit. Tôi ghi rõ license MIT, khuyến khích đóng góp.
  • Tài liệu đầy đủ: README, DEBUGGING-GUIDE.md trên 600 dòng (tab, metric, workflow).
  • Test scenario: README cung cấp demo component, QA copy/paste ngay.
  • Theo chuẩn web: FCP/LCP/TTFB và threshold CLS theo Google Web Vitals.
  • Kiến trúc: Background script + content script tách biệt, manifest V3.
  • Triết lý: Không suppress type error, khuyến khích best practice, đo lường trước khi tối ưu.
  • Sử dụng thực tế: Tôi dùng extension này mỗi ngày, mọi feedback tôi ghi lại thành issue/PR công khai.

8. Roadmap & lời hứa cá nhân

Tôi không dừng lại ở v1.0.0. Những việc đang nằm trong backlog cá nhân:

  1. Hỗ trợ React Server Components sâu hơn – track boundary server/client.
  2. Plugin rule tùy chỉnh – cho phép define company guideline (ví dụ: cảnh báo useLayoutEffect trong SSR).
  3. Session Replay nhẹ – export timeline + screenshot nhỏ.
  4. CI Integration – CLI so sánh snapshot, nhúng báo cáo vào PR.
  5. Telemetry tùy chọn – nếu người dùng bật, gửi thống kê ẩn danh để ưu tiên feature.
  6. Tài liệu tiếng Việt đầy đủ hơn – hỗ trợ cộng đồng React Việt.

Tôi cam kết: số hóa changelog rõ ràng, lắng nghe issue từ GitHub/Discord, và ưu tiên tiện ích thực tế. Tôi không muốn extension trở thành gánh nặng – nó phải là bạn đồng hành.


9. Kết lại – đừng để debugging “đánh cắp” tình yêu lập trình của chính bạn

Debug React có lẽ sẽ không bao giờ trở thành thú vui nhẹ nhàng. Nhưng tôi đã học cách biến nó thành nhiệm vụ có bản đồ, đèn pin và lối thoát rõ ràng. React Debugger giúp tôi:

  • Thay vì spam console.log, tôi nhìn vào timeline và hiểu chuỗi sự kiện.
  • Biết component nào rerender và vì sao.
  • Chuẩn hóa review (đính kèm snapshot, issue card).
  • Tự tin fix bug ngay cả trong bản demo live.
  • Giữ tinh thần ổn định sau nhiều giờ debugging.

Nếu bạn từng cảm thấy “React thực sự ghét mình”, hãy thử mở React Debugger, lướt qua từng tab. Bạn sẽ thấy câu chuyện mà ứng dụng của mình muốn nói – rõ ràng hơn, ít drama hơn, và quan trọng nhất: tiết kiệm thời gian để xây tính năng mới.

React Debugger không phải cây đũa thần, nhưng nó là chiếc kính hiển vi giúp tôi nhìn ra điều mắt thường bỏ lỡ. Và khi tôi tiếp tục đẩy những cập nhật mới, tôi luôn nhớ rằng: mình vẫn đang lăn tảng đá mỗi ngày, nhưng lần này có một công cụ đáng tin cậy đồng hành, để con đường phía trước bớt dốc hơn.

The post Từ Bế Tắc Debugging Đến Kiểm Soát Hoàn Toàn: Hành Trình Xây Dựng React Debugger Extension appeared first on Th?nk And Grow.

]]>
Mastering Rive Animation: A Complete Guide for React Developers https://blog.thnkandgrow.com/mastering-rive-animation-a-complete-guide-for-react-developers/ Mon, 15 Dec 2025 11:43:47 +0000 https://blog.thnkandgrow.com/?p=2562 In modern web development, creating lively and exciting user experiences (UX) requires more than just simple CSS transitions. We need complex, interactive animations that look great but don’t slow down the app. This is why Rive has become a powerful “secret weapon” in our technology stack. Today, let’s explore the full process of using Rive […]

The post Mastering Rive Animation: A Complete Guide for React Developers appeared first on Th?nk And Grow.

]]>
In modern web development, creating lively and exciting user experiences (UX) requires more than just simple CSS transitions. We need complex, interactive animations that look great but don’t slow down the app. This is why Rive has become a powerful “secret weapon” in our technology stack.

Today, let’s explore the full process of using Rive in our project, from understanding what it is to designing the architecture and implementing it using our real source code.


1. Rive Basics – From Design to Code

Before looking at the code, let’s understand the “ingredients” we are using. Understanding this process helps Developers and Designers work together better.

1. What is Rive? And How Do We Create It?

Rive is a complete ecosystem that includes a Design Tool (Editor) and a Runtime engine for code. It is different from Lottie (which just plays a JSON file) or Video. Rive acts like a real interactive machine.

Rive-flow

The Workflow:
Working with Rive is like combining Figma (for drawing) and After Effects (for movement), plus a bit of logic like Unity games.

  1. Design:
    • Designers use the Rive Editor on the web or desktop.
    • They can draw directly in Rive or import items from Figma.
    • Tip: Always name layers clearly (e.g., “UserAvatar”, “ScoreText”) so developers can find them easily in the code.
  2. Animate:
    • Designers use a Timeline to create movements (like Run, Jump, Idle).
    • Rive uses “bones” (skeletal animation), making characters move very smoothly.
  3. State Machine (The Logic):
    • This is the best part. Designers connect animations using logic.
    • Example: Switch from Idle to Running when the input isRunning is true.
    • Dev & Design Collaboration: We need to agree on the Input names (like Triggers, Numbers, Booleans) so React can control the animation perfectly.

2. The Difference Between .REV and .RIV

Many people get confused by these two file types.

  • .REV (Source File): This is the project file. It contains everything uncompressed. It is like a .PSD file in Photoshop. You keep this safe to edit later. Do not put this in your app code.
  • .RIV (Runtime File): This is the final product. It is binary, optimized, and very small. It is ready to run on the web. This is what we put in our src/assets folder.

3. Where to Find Free Rive Files?

If you want to practice but don’t have a designer, check out the Rive Community. It is like “GitHub for Animations.” You can search for “Loading” or “Button,” click “Remix,” see how they made it, and export the .riv file for free.

4. Playground


2. Technical Implementation in Our Architecture

To avoid repeating code and to keep our project clean, we don’t use the standard useRive library everywhere. Instead, we built a strong system around a custom hook called useRiveAnimation.

1. Project Structure

Based on our current codebase, here is how we organize things:

  • src/constants/rive.js: We define Artboard names, State Machines, and Input names here. This prevents spelling mistakes.
  • src/utils/riveUtils.js: Helper functions to create configurations quickly.
  • src/hooks/useRiveAnimation.js: The “heart” of our system. It handles loading, updates, and events.
  • src/view/shared/.../Templates: The actual UI components (like Popups, Banners, Widgets) that use the hook.
rive-architecture

2. Deep Dive: The useRiveAnimation Hook

This hook solves the hard problems: Loading states, Error handling, and most importantly, Dynamic Content Updates (changing text or images inside the animation).

update-content-by-rive

How it works:
The hook accepts a config object with src, artboard, and stateMachines.

// A simplified look at src/hooks/useRiveAnimation.js
const { rive, RiveComponent } = useRive({
    src: finalSrc,
    artboard: artboard,
    stateMachines: stateMachines,
    autoplay: autoplay,
    // ...
});

Key Feature: Dynamic Updates
We can change text (like a countdown timer) or images (like a user avatar) inside the running animation file using updateMultipleContents.

We support different RiveFieldTypes:

  • String: Change text content.
  • Image: Swap an image inside the animation.
  • Trigger/Boolean/Number: Control the logic/flow of the animation.

The code uses Promise.all to update everything at the same time for better performance:

// Efficient batch updating
const updateMultipleContents = useCallback(async (updates, artboardPath) => {
    // ... logic to find the view model ...
    const promises = updates.map(({ path, type, value }) => {
        switch (type) {
            case RiveFieldType.String: return updateStringValue(vmi, path, value);
            case RiveFieldType.Image: return updateImageValue(vmi, path, value);
            // ... handle other types
        }
    });
    await Promise.allSettled(promises);
}, [rive]);

3. How to Implement (Step-by-Step Guide)

Let’s imagine we are building a Countdown Widget (similar to WidgetManager/Templates/RiveAnimationTemplate.jsx).

Step 1: Prepare Constants

Define the Inputs that the Designer created in the Rive file.

// src/constants/rive.js
export const WIDGET_STATE_MACHINE = "Widget SM";
export const RiveInputs = {
    WidgetIn: "Widget In",   // Trigger: Play appear animation
    WidgetHover: "Hover",    // Boolean: Is mouse hovering?
};
export const RiveFields = {
    Time: "Timer/Time",      // Path to the text object in Rive
};

Step 2: Use the Hook in Your Component

Connect the hook. Always check isLoaded before showing the component.

const WidgetRive = ({ endTime }) => {
    const { 
        RiveComponent, 
        isLoaded, 
        updateMultipleContents, 
        triggerStateMachineInput 
    } = useRiveAnimation({
        src: "assets/widget.riv",
        artboard: "Main",
        stateMachines: WIDGET_STATE_MACHINE,
        autoplay: false, // We will play it manually later
    });

    // Update the timer every second
    useEffect(() => {
        if (isLoaded && endTime) {
             const timeStr = calculateTimeLeft(endTime);
             // Send new text to Rive
             updateMultipleContents([
                 new RivePropertyUpdate(RiveFields.Time, RiveFieldType.String, timeStr)
             ]);
        }
    }, [isLoaded, endTime]);

    return (
        <div className="widget-container">
            {!isLoaded && <CircularProgress />} {/* Show loading spinner */}
            <RiveComponent />
        </div>
    );
};

Step 3: Handling Interactions

In our BannerManager, we handle user clicks and hovers easily:

const handleMouseEnter = () => {
    // Tell Rive the mouse is over the banner
    triggerStateMachineInput(WIDGET_STATE_MACHINE, RiveInputs.WidgetHover, true);
};

const handleMouseLeave = () => {
    triggerStateMachineInput(WIDGET_STATE_MACHINE, RiveInputs.WidgetHover, false);
};

4. Best Practices & Tips

To make your animations smooth (60 FPS) and bug-free, follow these tips from our source code:

  1. Caching View Models:
    Our hook caches the instance (vmiDataRef). This is crucial. If you update a timer every second without caching, Rive has to search for the text object 60 times a minute, which causes lag.
  2. Resource Load Guard:
    Don’t render the Rive component until the file is actually downloaded, especially in Popups. <ResourceLoadGuard enabled={open} rives={[{ src: fileSrc }]}> <PopupBase>...</PopupBase> </ResourceLoadGuard>
  3. Prevent “Flickering”:
    Sometimes Rive shows the default text (“Text”) for a split second before your data loads. To fix this:
    • Set autoplay: false initially.
    • Wait for isLoaded.
    • Call updateMultipleContents to set your data.
    • Then call play().
  4. Handling Errors:
    Always have a Plan B. If the .riv file fails to load (404 error), the isError variable in the hook will be true. Use this to show a static image or a close button so the user isn’t stuck.

The Last Word

Rive is more than just a decoration tool. It separates the movement logic from the React code. This allows Designers to make things beautiful and Developers to focus on the data.

By mastering the useRiveAnimation hook, you can build Widgets, Banners, and Popups that feel premium and incredibly smooth. Happy coding!

The post Mastering Rive Animation: A Complete Guide for React Developers appeared first on Th?nk And Grow.

]]>