
100 câu hỏi phỏng vấn ReacJS level middle-senior kèm lời giải chi tiết từ A-Z
1. React Reconciliation là gì? React sử dụng thuật toán nào để tối ưu quá trình này?
React Reconciliation là quá trình React xác định sự khác biệt giữa Virtual DOM cũ và mới, sau đó cập nhật UI một cách hiệu quả. Thuật toán React sử dụng là Diffing Algorithm, trong đó React tối ưu việc so sánh theo hai nguyên tắc chính:
- Nếu hai phần tử có kiểu khác nhau (
divthànhspan,h1thànhp), React sẽ loại bỏ node cũ và tạo lại node mới thay vì cập nhật từng thuộc tính. - Khi render danh sách, React sử dụng key để xác định phần tử nào giữ nguyên, phần tử nào thay đổi nhằm giảm số lần cập nhật DOM không cần thiết.
function App() {
const [toggle, setToggle] = React.useState(true);
return (
<div>
<button onClick={() => setToggle(!toggle)}>Toggle</button>
{toggle ? <h1 key="title">Hello</h1> : <p key="title">World</p>}
</div>
);
}
Nếu key giống nhau, React giữ lại phần tử cũ và chỉ thay đổi nội dung. Nếu key khác nhau, React xóa phần tử cũ và tạo lại hoàn toàn node mới.
2. React Hooks hoạt động như thế nào ở mức độ sâu hơn?
React Hooks hoạt động dựa trên một danh sách liên kết được lưu trữ trong Fiber Tree. Khi một function component render, React duyệt danh sách hook theo đúng thứ tự gọi để gán lại giá trị trước đó.
function Counter() {
const [count, setCount] = React.useState(0);
console.log("Render:", count);
return (
<button onClick={() => setCount(count + 1)}>Click {count}</button>
);
}
- React duy trì một danh sách hooks theo thứ tự gọi.
- Khi
useState()chạy, nó lấy giá trị từ danh sách này và giữ nguyên vị trí trong re-render. - Nếu thứ tự gọi
useState()thay đổi giữa các lần render (do có điều kiện trước hook), React sẽ gặp lỗi.
3. Custom Hook hoạt động như thế nào? Tại sao phải dùng Custom Hook thay vì Component?
Custom Hook giúp trừu tượng hóa logic tái sử dụng mà không làm phình to Component hoặc sử dụng HOC. Chúng hoạt động như một function bình thường nhưng có thể gọi hooks bên trong.
function useFetch(url) {
const [data, setData] = React.useState(null);
const [loading, setLoading] = React.useState(true);
React.useEffect(() => {
fetch(url)
.then(res => res.json())
.then(data => {
setData(data);
setLoading(false);
});
}, [url]);
return { data, loading };
}
function Users() {
const { data, loading } = useFetch("https://jsonplaceholder.typicode.com/users");
if (loading) return <p>Loading...</p>;
return <ul>{data.map(user => <li key={user.id}>{user.name}</li>)}</ul>;
}
- Custom Hook giúp component trở nên nhỏ gọn, dễ bảo trì.
- Có thể tái sử dụng nhiều lần mà không cần thay đổi logic trong component chính.
4. useMemo và useCallback khác nhau như thế nào? Khi nào dùng từng cái?
useMemotối ưu hiệu suất bằng cách lưu trữ giá trị tính toán, chỉ tính lại khi dependencies thay đổi.useCallbacktối ưu việc tạo lại function, chỉ tạo lại function khi dependencies thay đổi.
function ExpensiveComponent({ num }) {
const result = React.useMemo(() => {
console.log("Calculating...");
return num * 2;
}, [num]);
return <p>Result: {result}</p>;
}
function Parent() {
const [count, setCount] = React.useState(0);
const logMessage = React.useCallback(() => {
console.log("Clicked", count);
}, [count]);
return <Child logMessage={logMessage} />;
}
function Child({ logMessage }) {
React.useEffect(() => {
logMessage();
}, [logMessage]);
return <p>Check console</p>;
}
useMemogiúp tránh tính toán lại khi không cần thiết.useCallbackgiúp tránh việc tạo mới function không cần thiết, đặc biệt khi truyền function vào component con.
5. React Concurrent Mode hoạt động như thế nào?
React Concurrent Mode cho phép UI giữ được phản hồi nhanh hơn bằng cách tạm dừng, tiếp tục hoặc hủy bỏ render khi cần thiết. Điều này giúp giảm thiểu độ trễ UI khi có nhiều cập nhật xảy ra đồng thời.
const fetchData = () => {
return new Promise(resolve => setTimeout(() => resolve("Data Loaded"), 2000));
};
const resource = fetchData();
function FetchComponent() {
const data = React.use(resource);
return <h1>{data}</h1>;
}
function App() {
return (
<React.Suspense fallback={<h1>Loading...</h1>}>
<FetchComponent />
</React.Suspense>
);
}
- React có thể tạm dừng rendering khi đang tải dữ liệu.
- Giúp giữ trải nghiệm mượt mà thay vì bị “đơ” khi có tác vụ nặng.
6. React Server Components là gì? Có gì khác với Client Components?
React Server Components (RSC) cho phép render một phần UI trên server trước khi gửi đến client. Điều này giúp giảm tải cho browser, giảm kích thước bundle, và tăng tốc độ tải trang.
// Server Component (chạy trên server)
export default async function ServerComponent() {
const data = await fetch("https://api.example.com/data").then(res => res.json());
return <h1>{data.title}</h1>;
}
// Client Component (chạy trên browser)
"use client";
export default function ClientComponent() {
const [count, setCount] = React.useState(0);
return <button onClick={() => setCount(count + 1)}>Click {count}</button>;
}
- Server Component chạy trên server, không có state, không có sự kiện tương tác.
- Client Component chạy trên browser, có thể dùng state và sự kiện.
- Tách biệt giúp tối ưu hiệu suất trang web.
7. React Fiber là gì? Tại sao React sử dụng Fiber thay vì Stack Reconciliation cũ?
React Fiber là kiến trúc mới của React giúp tối ưu quá trình cập nhật UI bằng cách chia nhỏ quá trình rendering thành nhiều phần nhỏ hơn (work units), cho phép React có thể tạm dừng, tiếp tục hoặc hủy bỏ rendering khi cần thiết.
Trước đây, React sử dụng Stack Reconciliation, xử lý toàn bộ cập nhật UI theo kiểu đệ quy đồng bộ, nghĩa là khi một component re-render, React sẽ duyệt qua toàn bộ cây component mà không thể tạm dừng giữa chừng. Điều này gây ra vấn đề lag khi có nhiều component cần cập nhật cùng lúc.
Fiber giải quyết vấn đề này bằng cách sử dụng một cấu trúc dữ liệu mới (Fiber Tree) giúp:
- Chia nhỏ rendering thành nhiều work units, có thể tạm dừng và tiếp tục sau khi browser có thời gian rảnh (cooperative scheduling).
- Hủy bỏ hoặc ưu tiên các cập nhật UI quan trọng trước các cập nhật ít quan trọng hơn.
- Hỗ trợ hiệu ứng UI mượt mà hơn khi cập nhật state.
function App() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
console.log("Effect chạy sau mỗi lần render");
});
return (
<button onClick={() => setCount(count + 1)}>Click {count}</button>
);
}
React Fiber cho phép tạm dừng hiệu ứng UI nặng (như animation, data fetching) để tránh chặn UI chính, giúp trải nghiệm mượt hơn.
8. Suspense và React.lazy hoạt động như thế nào?
Suspense cho phép React trì hoãn render một phần của component tree cho đến khi dữ liệu sẵn sàng. Trong khi đó, React.lazy() giúp load các component một cách lazy-loading (chỉ tải component khi cần thiết).
const LazyComponent = React.lazy(() => import("./LazyComponent"));
function App() {
return (
<React.Suspense fallback={<p>Loading...</p>}>
<LazyComponent />
</React.Suspense>
);
}
React.lazy()chỉ tải component khi cần, giúp giảm kích thước bundle.React.Suspensecho phép hiển thị một fallback UI trong khi chờ component tải về.
9. Context API hoạt động như thế nào? Khi nào nên dùng thay vì Redux?
Context API cho phép chia sẻ state giữa nhiều component mà không cần truyền props xuống từng cấp.
const ThemeContext = React.createContext();
function ThemeProvider({ children }) {
const [theme, setTheme] = React.useState("light");
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
function ThemedComponent() {
const { theme, setTheme } = React.useContext(ThemeContext);
return (
<button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
Current Theme: {theme}
</button>
);
}
function App() {
return (
<ThemeProvider>
<ThemedComponent />
</ThemeProvider>
);
}
- Context API phù hợp cho dữ liệu cần chia sẻ trong phạm vi nhỏ (theme, auth, ngôn ngữ).
- Redux phù hợp với ứng dụng phức tạp, có nhiều state cần quản lý từ nhiều nơi.
10. HOC (Higher-Order Component) là gì? So sánh HOC với Render Props?
HOC là một function nhận một component và trả về một component mới, giúp tái sử dụng logic mà không cần thay đổi component gốc.
function withLogger(WrappedComponent) {
return function EnhancedComponent(props) {
console.log("Component Rendered:", WrappedComponent.name);
return <WrappedComponent {...props} />;
};
}
function Hello() {
return <h1>Hello</h1>;
}
const EnhancedHello = withLogger(Hello);
function App() {
return <EnhancedHello />;
}
Render Props cũng giúp tái sử dụng logic bằng cách truyền function vào component con.
function DataFetcher({ render }) {
const [data, setData] = React.useState(null);
React.useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then(res => res.json())
.then(setData);
}, []);
return render(data);
}
function App() {
return (
<DataFetcher render={data => (data ? <p>{data.title}</p> : <p>Loading...</p>)} />
);
}
- HOC giúp thêm behavior vào component mà không thay đổi component gốc nhưng có thể gây wrapper hell khi có quá nhiều HOC lồng nhau.
- Render Props giúp truyền logic vào component con một cách linh hoạt hơn.
11. useReducer hoạt động như thế nào? So sánh với useState?
useReducer giúp quản lý state phức tạp hơn bằng cách sử dụng reducer function thay vì gọi setState trực tiếp.
function reducer(state, action) {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
default:
return state;
}
}
function Counter() {
const [state, dispatch] = React.useReducer(reducer, { count: 0 });
return (
<div>
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
<span>{state.count}</span>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
</div>
);
}
useStatephù hợp với state đơn giản.useReducerphù hợp với state có nhiều logic phức tạp hoặc khi state cần được quản lý dựa trên nhiều hành động khác nhau.
12. React Portals là gì? Khi nào nên dùng?
React Portals cho phép render một component ra ngoài DOM tree của component cha mà vẫn giữ được state và context.
function Modal({ children }) {
return ReactDOM.createPortal(
<div className="modal">{children}</div>,
document.getElementById("modal-root")
);
}
function App() {
const [show, setShow] = React.useState(false);
return (
<div>
<button onClick={() => setShow(true)}>Show Modal</button>
{show && <Modal><p>Modal Content</p></Modal>}
</div>
);
}
- Portals hữu ích khi cần tạo modal, tooltip, dropdown không bị ảnh hưởng bởi overflow, position hay z-index của parent component.
13. useTransition và useDeferredValue khác nhau như thế nào?
useTransitiongiúp đánh dấu một cập nhật là “chậm” (non-blocking), React có thể bỏ qua nếu có cập nhật quan trọng hơn.useDeferredValuetrì hoãn cập nhật của một giá trị để tránh làm chậm UI chính.
function App() {
const [query, setQuery] = React.useState("");
const [isPending, startTransition] = React.useTransition();
return (
<div>
<input onChange={e => startTransition(() => setQuery(e.target.value))} />
{isPending ? <p>Loading...</p> : <p>Search: {query}</p>}
</div>
);
}
function App() {
const [query, setQuery] = React.useState("");
const deferredQuery = React.useDeferredValue(query);
return (
<div>
<input onChange={e => setQuery(e.target.value)} />
<p>Search: {deferredQuery}</p>
</div>
);
}
useTransitionưu tiên trải nghiệm UI bằng cách đánh dấu cập nhật nào quan trọng hơn.useDeferredValuegiúp tối ưu performance bằng cách trì hoãn giá trị state không quan trọng.
14. Strict Mode trong React là gì? Tại sao cần dùng?
Strict Mode là một công cụ giúp phát hiện các vấn đề tiềm ẩn trong ứng dụng React trong môi trường phát triển. Nó không ảnh hưởng đến behavior của ứng dụng trên production.
Khi bật StrictMode, React sẽ:
- Gọi
useEffectvàuseLayoutEffecthai lần trong chế độ phát triển để phát hiện các side effects không an toàn. - Cảnh báo về API cũ không còn được khuyến nghị.
- Phát hiện việc sử dụng các function component không tuân thủ quy tắc hooks.
import React from "react";
function App() {
return (
<React.StrictMode>
<MyComponent />
</React.StrictMode>
);
}
Nên sử dụng StrictMode để phát hiện lỗi tiềm ẩn trước khi deploy ứng dụng.
15. React.memo hoạt động như thế nào? Khi nào nên dùng?
React.memo là một HOC giúp memo hóa component để ngăn chặn re-render không cần thiết nếu props không thay đổi.
const MemoizedComponent = React.memo(function MyComponent({ name }) {
console.log("Rendered:", name);
return <h1>Hello, {name}</h1>;
});
function App() {
const [count, setCount] = React.useState(0);
return (
<div>
<button onClick={() => setCount(count + 1)}>Click {count}</button>
<MemoizedComponent name="John" />
</div>
);
}
- Nếu
namekhông thay đổi,MemoizedComponentkhông bị re-render. React.memochỉ tối ưu với component có props tĩnh. Nếu props là object hoặc function, cần kết hợp vớiuseMemohoặcuseCallbackđể tránh tham chiếu mới.
16. useLayoutEffect khác gì so với useEffect? Khi nào dùng useLayoutEffect?
useEffectchạy sau khi render và paint (khi UI đã được cập nhật trên màn hình).useLayoutEffectchạy ngay sau render nhưng trước khi paint, giúp cập nhật DOM trước khi hiển thị lên UI.
function Example() {
const ref = React.useRef(null);
React.useLayoutEffect(() => {
console.log("Bounding rect:", ref.current.getBoundingClientRect());
});
return <div ref={ref}>Hello</div>;
}
useLayoutEffecthữu ích khi cần đo đạc kích thước DOM hoặc thay đổi layout trước khi hiển thị.- Nếu không cần thao tác DOM trực tiếp, nên dùng
useEffectđể tránh block rendering.
17. useRef có thể làm gì ngoài việc truy cập DOM?
Ngoài việc truy cập DOM element, useRef có thể lưu trữ giá trị không gây re-render khi thay đổi.
function Timer() {
const countRef = React.useRef(0);
React.useEffect(() => {
const interval = setInterval(() => {
countRef.current += 1;
console.log(countRef.current);
}, 1000);
return () => clearInterval(interval);
}, []);
return <p>Open console to see updates</p>;
}
useRefkhông trigger re-render khi giá trị thay đổi, giúp tối ưu performance.- Dùng để lưu trữ giá trị giữa các render mà không làm ảnh hưởng đến UI.
18. useImperativeHandle và forwardRef hoạt động như thế nào? Khi nào cần dùng?
useImperativeHandle kết hợp với forwardRef cho phép component con cung cấp các method tùy chỉnh cho component cha.
const Child = React.forwardRef((props, ref) => {
const inputRef = React.useRef(null);
React.useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} />;
});
function Parent() {
const childRef = React.useRef(null);
return (
<div>
<button onClick={() => childRef.current.focus()}>Focus Input</button>
<Child ref={childRef} />
</div>
);
}
- Hữu ích khi cần expose method từ component con cho component cha.
- Tránh việc dùng
reftrực tiếp trên component function.
19. React Hydration là gì? Khi nào cần dùng?
React Hydration xảy ra khi React gắn kết (attach) event listener và state vào markup HTML đã được server render trước đó.
import { hydrateRoot } from "react-dom/client";
hydrateRoot(document.getElementById("root"), <App />);
- Hydration giúp giảm thời gian tải trang bằng cách sử dụng SSR (Server Side Rendering).
- Nếu markup trên server và client không khớp, React sẽ cảnh báo lỗi hydration.
20. Error Boundary là gì? React có hỗ trợ Error Boundary cho function component không?
Error Boundary là một component class dùng để bắt lỗi trong các component con và hiển thị fallback UI thay vì crash toàn bộ ứng dụng.
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
console.log("Error:", error, info);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
function BuggyComponent() {
throw new Error("This is a test error");
}
function App() {
return (
<ErrorBoundary>
<BuggyComponent />
</ErrorBoundary>
);
}
- React không hỗ trợ Error Boundary cho function component, cần dùng class component.
- Hữu ích khi cần bảo vệ UI khỏi bị crash do lỗi runtime.
21. Hàm getDerivedStateFromProps hoạt động như thế nào? Có nên dùng nó không?
getDerivedStateFromProps là một phương thức static trong class component, được gọi trước mỗi lần render khi props thay đổi.
class Example extends React.Component {
constructor(props) {
super(props);
this.state = { value: props.value };
}
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.value !== prevState.value) {
return { value: nextProps.value };
}
return null;
}
render() {
return <h1>{this.state.value}</h1>;
}
}
- Không nên lạm dụng
getDerivedStateFromProps, vì nó có thể gây double re-render không cần thiết. - Trong hầu hết các trường hợp,
useEffecthoặccomponentDidUpdatelà lựa chọn tốt hơn.
22. React Suspense cho Data Fetching hoạt động như thế nào?
React Suspense cho phép trì hoãn rendering cho đến khi dữ liệu sẵn sàng mà không cần quản lý loading state thủ công.
const resource = fetchData();
function DataComponent() {
const data = resource.read();
return <h1>{data}</h1>;
}
function App() {
return (
<React.Suspense fallback={<p>Loading...</p>}>
<DataComponent />
</React.Suspense>
);
}
- Suspense giúp tối ưu data fetching bằng cách trì hoãn component cho đến khi có dữ liệu.
- Giảm boilerplate code so với cách quản lý loading state thủ công.
23. React Server Actions là gì? Khác gì với API truyền thống?
React Server Actions là một cách để xử lý dữ liệu trực tiếp trên server mà không cần gửi request từ client như API truyền thống. Điều này giúp tối ưu hiệu suất, giảm tải công việc trên frontend và loại bỏ nhiều logic xử lý state không cần thiết.
"use server";
export async function saveUser(data) {
const response = await fetch("https://api.example.com/user", {
method: "POST",
body: JSON.stringify(data),
headers: { "Content-Type": "application/json" },
});
return response.json();
}
import { saveUser } from "./actions";
function Form() {
async function handleSubmit(event) {
event.preventDefault();
const formData = new FormData(event.target);
await saveUser(Object.fromEntries(formData));
}
return (
<form onSubmit={handleSubmit}>
<input name="name" placeholder="Enter name" required />
<button type="submit">Submit</button>
</form>
);
}
- Không cần fetch API từ client, giảm độ phức tạp của mã nguồn.
- Tránh rò rỉ dữ liệu trên client, vì logic xử lý được giữ trên server.
- Không cần useEffect hay fetch API trong component, giúp mã nguồn sạch hơn.
24. Middleware trong Next.js hoạt động như thế nào? Khi nào cần dùng?
Middleware trong Next.js cho phép chặn request trước khi nó được xử lý bởi API routes hoặc page, giúp điều hướng, bảo mật, hoặc thực hiện các thao tác như ghi log request.
import { NextResponse } from "next/server";
export function middleware(req) {
const url = req.nextUrl.clone();
if (!req.cookies.get("auth")) {
url.pathname = "/login";
return NextResponse.redirect(url);
}
return NextResponse.next();
}
export const config = {
matcher: "/dashboard/:path*",
};
- Tự động chạy trước mỗi request, không cần chỉnh sửa page component.
- Hữu ích cho xác thực (authentication), A/B testing, hoặc rewrite URL.
25. Cơ chế Caching của Next.js hoạt động như thế nào?
Next.js cung cấp nhiều cơ chế caching để tối ưu hiệu suất, bao gồm:
- Static Generation (SSG): Trang được tạo sẵn khi build, không cần fetch dữ liệu mỗi request.
- Server-Side Rendering (SSR): Fetch dữ liệu mỗi request, không cache.
- Incremental Static Regeneration (ISR): Cho phép cập nhật dữ liệu định kỳ mà không cần build lại toàn bộ site.
export async function getStaticProps() {
const res = await fetch("https://api.example.com/data");
const data = await res.json();
return { props: { data }, revalidate: 10 };
}
getStaticProps: Cache dữ liệu tĩnh, cập nhật mỗirevalidategiây.getServerSideProps: Luôn tải dữ liệu mới mỗi request.revalidate: Cho phép cập nhật dữ liệu một cách incremental mà không cần rebuild toàn bộ site.
26. React DevTools hoạt động như thế nào? Cách debug hiệu quả với React DevTools?
React DevTools là công cụ giúp debug component tree, state, props, và đo performance của ứng dụng. Một số tính năng quan trọng:
- Component Tree: Xem state, props, và kiểm tra re-render.
- Profiler: Đo thời gian render của từng component để tìm ra hiệu suất kém.
- Highlight Updates: Xác định component nào re-render không cần thiết.
function App() {
const [count, setCount] = React.useState(0);
return (
<button onClick={() => setCount(count + 1)}>Click {count}</button>
);
}
- Dùng Profiler để kiểm tra component nào render quá nhiều.
- Kiểm tra Context API state để tránh truyền dữ liệu không cần thiết.
27. React Suspense với Streaming hoạt động như thế nào?
React Suspense với Streaming giúp React gửi dữ liệu từng phần xuống client thay vì đợi tải toàn bộ nội dung trước khi hiển thị. Điều này cải thiện tốc độ load trang trong SSR + Suspense.
import { Suspense } from "react";
function Loading() {
return <p>Loading...</p>;
}
export default function App() {
return (
<Suspense fallback={<Loading />}>
<AsyncComponent />
</Suspense>
);
}
- Phần nào tải xong trước sẽ hiển thị trước, không cần chờ toàn bộ component.
- Cải thiện thời gian tải trang trong môi trường SSR.
28. Tối ưu Performance với React 18 startTransition()
startTransition() giúp React đánh dấu các cập nhật không quan trọng để giữ UI chính mượt mà hơn.
function App() {
const [query, setQuery] = React.useState("");
const [isPending, startTransition] = React.useTransition();
return (
<div>
<input
onChange={(e) => {
startTransition(() => setQuery(e.target.value));
}}
/>
{isPending ? <p>Loading...</p> : <p>Search: {query}</p>}
</div>
);
}
- Tăng hiệu suất UI, tránh giật lag khi cập nhật state.
- Hữu ích khi làm việc với danh sách lớn hoặc dữ liệu tải chậm.
29. React với WebSockets để tạo ứng dụng realtime
WebSockets cho phép React giao tiếp với server theo thời gian thực mà không cần request HTTP liên tục.
const socket = new WebSocket("wss://example.com");
socket.onmessage = (event) => {
console.log("Received:", event.data);
};
- Dùng WebSockets để xây dựng chat app, cập nhật dữ liệu realtime.
- Hữu ích cho ứng dụng tài chính, giao dịch chứng khoán, IoT, hoặc multiplayer game.
30. React với PWA (Progressive Web Apps) hoạt động như thế nào?
React có thể tạo PWA bằng cách thêm service worker để hỗ trợ caching, offline mode và push notification.
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/sw.js").then(() => {
console.log("Service Worker Registered");
});
}
- Lưu trang để chạy offline mà không cần mạng.
- Hỗ trợ push notifications như native app.
31. React với WebAssembly (WASM) có thể làm gì?
React có thể sử dụng WebAssembly để chạy mã hiệu suất cao như C++ hoặc Rust trực tiếp trên browser.
import init, { add } from "./wasm_module";
async function run() {
await init();
console.log(add(2, 3));
}
- Tăng hiệu suất xử lý số liệu và đồ họa.
- Có thể viết phần backend xử lý nặng bằng Rust + WebAssembly.
32. Xây dựng Design System với React Component Library
Một cách tối ưu để làm Design System là dùng Storybook hoặc Chakra UI để tạo thư viện component có thể tái sử dụng.
import { Button } from "@chakra-ui/react";
function MyButton() {
return <Button colorScheme="blue">Click Me</Button>;
}
- Storybook giúp test component độc lập mà không cần chạy app.
- Dùng ThemeProvider để quản lý style động trong toàn bộ hệ thống.
33. React với GraphQL hoạt động như thế nào?
React có thể kết hợp với Apollo Client để fetch dữ liệu từ GraphQL API một cách tối ưu.
import { useQuery, gql } from "@apollo/client";
const GET_USERS = gql`
query {
users {
id
name
}
}
`;
function Users() {
const { loading, error, data } = useQuery(GET_USERS);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error!</p>;
return <ul>{data.users.map(user => <li key={user.id}>{user.name}</li>)}</ul>;
}
- Giảm over-fetching dữ liệu so với REST API.
- Tối ưu performance với caching của Apollo Client.
34. React với Zustand: Khi nào nên dùng Zustand thay vì Redux?
Zustand là một thư viện quản lý state nhẹ hơn Redux, không cần boilerplate nhiều như Redux.
import create from "zustand";
const useStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
}));
function Counter() {
const { count, increment } = useStore();
return <button onClick={increment}>Click {count}</button>;
}
- Không cần reducer hay action như Redux, giúp code gọn hơn.
- Hỗ trợ state persistence và middleware dễ dàng hơn.
35. React với React Query: Khi nào nên dùng?
React Query giúp tối ưu việc fetch dữ liệu và caching trong React, thay thế cho việc quản lý state thủ công với useState và useEffect.
import { useQuery } from "react-query";
function fetchData() {
return fetch("https://jsonplaceholder.typicode.com/users").then((res) => res.json());
}
function Users() {
const { data, isLoading, error } = useQuery("users", fetchData);
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error!</p>;
return <ul>{data.map((user) => <li key={user.id}>{user.name}</li>)}</ul>;
}
- Tự động caching dữ liệu, tránh fetch lại không cần thiết.
- Tự động retry khi có lỗi, giúp tối ưu trải nghiệm người dùng.
- Hỗ trợ pagination, infinite scrolling dễ dàng hơn.
36. React với RxJS: Khi nào cần Reactive Programming trong React?
RxJS giúp xử lý các sự kiện bất đồng bộ như WebSockets, streaming data, và xử lý debounce/throttle dễ dàng hơn.
import { useState, useEffect } from "react";
import { fromEvent } from "rxjs";
import { debounceTime, map } from "rxjs/operators";
function SearchBar() {
const [query, setQuery] = useState("");
useEffect(() => {
const searchInput = document.getElementById("search");
const subscription = fromEvent(searchInput, "input")
.pipe(
debounceTime(300),
map((event) => event.target.value)
)
.subscribe(setQuery);
return () => subscription.unsubscribe();
}, []);
return <input id="search" placeholder="Search..." />;
}
- Hữu ích khi xử lý debounce/throttle, cancel request API.
- Thích hợp cho realtime data với WebSockets, SSE (Server-Sent Events).
37. React với WebRTC: Cách tạo ứng dụng gọi video P2P?
WebRTC giúp React xây dựng ứng dụng gọi video hoặc chia sẻ màn hình trực tiếp trên trình duyệt mà không cần server trung gian.
const peerConnection = new RTCPeerConnection();
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then((stream) => {
document.getElementById("video").srcObject = stream;
stream.getTracks().forEach((track) => peerConnection.addTrack(track, stream));
});
peerConnection.ontrack = (event) => {
document.getElementById("remoteVideo").srcObject = event.streams[0];
};
- Không cần backend để xử lý media, giúp ứng dụng hoạt động nhanh hơn.
- Có thể dùng cho chat video, chia sẻ màn hình, hoặc ứng dụng IoT.
38. React với Tailwind CSS: Cách tối ưu CSS trong React?
Tailwind CSS giúp viết CSS tiện lợi hơn trong JSX mà không cần tạo file .css.
function Button() {
return <button className="bg-blue-500 text-white px-4 py-2 rounded">Click Me</button>;
}
- Không cần đặt tên class phức tạp, code CSS dễ đọc hơn.
- Hỗ trợ dark mode, responsive, animation sẵn có.
- Tương thích tốt với các framework như Next.js, Gatsby.
39. React với Electron: Cách tạo ứng dụng desktop bằng React?
Electron cho phép dùng React để xây dựng ứng dụng desktop đa nền tảng (Windows, macOS, Linux).
main.js (Electron Main Process)
const { app, BrowserWindow } = require("electron");
app.whenReady().then(() => {
const win = new BrowserWindow({ width: 800, height: 600 });
win.loadURL("http://localhost:3000");
});
React Component
function App() {
return <h1>React + Electron App</h1>;
}
- Dùng HTML, CSS, JavaScript để tạo ứng dụng desktop.
- Có thể tích hợp với Node.js để truy cập hệ thống file, API OS.
40. React với WebGL: Cách render đồ họa 3D trong React?
React có thể dùng Three.js hoặc React Three Fiber để tạo ứng dụng 3D, game, hoặc mô phỏng khoa học.
import { Canvas } from "@react-three/fiber";
function Scene() {
return (
<Canvas>
<mesh>
<boxGeometry args={[1, 1, 1]} />
<meshStandardMaterial color="blue" />
</mesh>
</Canvas>
);
}
- Hiển thị đồ họa 3D trực tiếp trong trình duyệt.
- Hữu ích cho game, AR/VR, và mô phỏng vật lý.
41. React với Machine Learning: Làm sao tích hợp AI vào React?
React có thể sử dụng TensorFlow.js để chạy model Machine Learning trực tiếp trên frontend.
import * as tf from "@tensorflow/tfjs";
async function loadModel() {
const model = await tf.loadLayersModel("/model.json");
return model;
}
- Chạy model AI trực tiếp trên trình duyệt, không cần backend.
- Hữu ích cho nhận diện hình ảnh, phân loại văn bản, chatbot AI.
42. React với Blockchain: Làm sao tích hợp Web3 vào React?
React có thể dùng Web3.js hoặc Ethers.js để kết nối với Ethereum blockchain, giúp xây dựng ứng dụng phi tập trung (DApp).
import { ethers } from "ethers";
async function connectWallet() {
if (window.ethereum) {
const provider = new ethers.providers.Web3Provider(window.ethereum);
await provider.send("eth_requestAccounts", []);
const signer = provider.getSigner();
console.log(await signer.getAddress());
}
}
- Có thể tạo ví crypto, giao dịch token, hoặc smart contract.
- Hữu ích cho DeFi, NFT marketplace, và DAO.
43. React với IoT: Cách kết nối React với thiết bị IoT?
React có thể kết nối với thiết bị IoT qua MQTT, WebSockets, hoặc HTTP API.
import mqtt from "mqtt";
const client = mqtt.connect("ws://broker.hivemq.com:8000/mqtt");
client.on("connect", () => {
client.subscribe("home/temperature");
});
client.on("message", (topic, message) => {
console.log(`Received: ${message.toString()}`);
});
- Có thể điều khiển thiết bị thông minh (smart home).
- Dùng để hiển thị dữ liệu cảm biến, theo dõi môi trường.
44. React với Edge Computing: Làm sao giảm tải cho server?
Edge Computing cho phép xử lý dữ liệu ngay tại client hoặc server gần nhất thay vì gửi tất cả request về backend.
export async function getEdgeData(req) {
const response = await fetch("https://api.example.com/data", { method: "GET" });
return response.json();
}
- Giảm độ trễ (latency) khi xử lý dữ liệu.
- Hữu ích cho ứng dụng AI, IoT, và streaming video.
45. React với Micro Frontends: Làm sao chia nhỏ ứng dụng thành nhiều phần độc lập?
Micro Frontends giúp chia nhỏ ứng dụng thành nhiều module độc lập, giúp bảo trì dễ dàng hơn và cho phép các nhóm làm việc trên các phần khác nhau mà không ảnh hưởng lẫn nhau.
Một cách phổ biến để triển khai Micro Frontends trong React là dùng Module Federation với Webpack:
Cấu hình Webpack cho ứng dụng Remote (Micro Frontend)
const { ModuleFederationPlugin } = require("webpack").container;
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: "remoteApp",
filename: "remoteEntry.js",
exposes: {
"./Button": "./src/Button",
},
shared: ["react", "react-dom"],
}),
],
};
Import Component từ Remote vào ứng dụng Host
import React from "react";
const RemoteButton = React.lazy(() => import("remoteApp/Button"));
function App() {
return (
<React.Suspense fallback={<p>Loading...</p>}>
<RemoteButton />
</React.Suspense>
);
}
- Tách biệt ứng dụng thành nhiều module nhỏ hơn, giúp dễ dàng phát triển theo nhóm độc lập.
- Có thể cập nhật từng phần mà không ảnh hưởng đến toàn bộ ứng dụng.
46. React với GraphQL Subscriptions: Làm sao nhận dữ liệu realtime từ GraphQL?
GraphQL Subscriptions cho phép React nhận dữ liệu realtime thông qua WebSockets, hữu ích cho chat, thông báo, hoặc cập nhật dữ liệu liên tục.
Cấu hình Apollo Client với WebSockets
import { ApolloClient, InMemoryCache, split, HttpLink } from "@apollo/client";
import { WebSocketLink } from "@apollo/client/link/ws";
import { getMainDefinition } from "@apollo/client/utilities";
const httpLink = new HttpLink({ uri: "https://api.example.com/graphql" });
const wsLink = new WebSocketLink({
uri: "wss://api.example.com/graphql",
options: { reconnect: true },
});
const link = split(
({ query }) => {
const definition = getMainDefinition(query);
return definition.kind === "OperationDefinition" && definition.operation === "subscription";
},
wsLink,
httpLink
);
const client = new ApolloClient({ link, cache: new InMemoryCache() });
Lắng nghe sự kiện với Subscription
import { useSubscription, gql } from "@apollo/client";
const MESSAGE_SUBSCRIPTION = gql`
subscription {
newMessage {
id
content
sender
}
}
`;
function Chat() {
const { data, loading } = useSubscription(MESSAGE_SUBSCRIPTION);
if (loading) return <p>Loading...</p>;
return <p>New Message: {data.newMessage.content}</p>;
}
- Giúp cập nhật dữ liệu realtime mà không cần polling.
- Tối ưu hiệu suất so với việc gửi request liên tục để kiểm tra dữ liệu mới.
47. React với Web Bluetooth API: Làm sao kết nối với thiết bị Bluetooth từ trình duyệt?
Web Bluetooth API cho phép React giao tiếp với các thiết bị ngoại vi hỗ trợ Bluetooth, hữu ích cho IoT và smart devices.
async function connectDevice() {
const device = await navigator.bluetooth.requestDevice({
acceptAllDevices: true,
optionalServices: ["battery_service"],
});
const server = await device.gatt.connect();
const service = await server.getPrimaryService("battery_service");
const characteristic = await service.getCharacteristic("battery_level");
const value = await characteristic.readValue();
console.log(`Battery level: ${value.getUint8(0)}%`);
}
- Hữu ích cho các ứng dụng smart home, wearable devices, và robotics.
- Có thể điều khiển hoặc thu thập dữ liệu từ thiết bị Bluetooth ngay trên trình duyệt.
48. React với Web Serial API: Làm sao giao tiếp với cổng USB từ trình duyệt?
Web Serial API cho phép giao tiếp với thiết bị ngoại vi thông qua cổng USB, hữu ích cho IoT, CNC, hoặc thiết bị công nghiệp.
async function connectSerial() {
const port = await navigator.serial.requestPort();
await port.open({ baudRate: 9600 });
const writer = port.writable.getWriter();
await writer.write(new TextEncoder().encode("Hello Device"));
writer.releaseLock();
}
- Có thể gửi và nhận dữ liệu từ các thiết bị phần cứng ngay trên trình duyệt.
- Hữu ích cho lập trình nhúng, giao tiếp với Arduino, Raspberry Pi.
49. React với WebXR API: Làm sao xây dựng ứng dụng VR/AR?
WebXR API cho phép React tạo ứng dụng thực tế ảo (VR) và thực tế tăng cường (AR) chạy trực tiếp trên trình duyệt mà không cần cài đặt phần mềm bổ sung.
Tạo một cảnh WebXR đơn giản với React Three Fiber
import { Canvas } from "@react-three/fiber";
import { VRButton, XR } from "@react-three/xr";
function Scene() {
return (
<Canvas>
<XR>
<VRButton />
<mesh>
<boxGeometry args={[1, 1, 1]} />
<meshStandardMaterial color="blue" />
</mesh>
</XR>
</Canvas>
);
}
- Có thể hiển thị mô hình 3D trực tiếp trên trình duyệt.
- Hữu ích cho game VR, hướng dẫn sản phẩm AR, hoặc mô phỏng khoa học.
50. React với AI Chatbot: Làm sao tích hợp ChatGPT vào React?
React có thể sử dụng OpenAI API để tạo chatbot thông minh tích hợp trực tiếp trong ứng dụng.
async function getChatResponse(message) {
const response = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer YOUR_OPENAI_API_KEY`,
},
body: JSON.stringify({
model: "gpt-4",
messages: [{ role: "user", content: message }],
}),
});
const data = await response.json();
return data.choices[0].message.content;
}
function Chat() {
const [message, setMessage] = React.useState("");
const [response, setResponse] = React.useState("");
async function handleSend() {
const reply = await getChatResponse(message);
setResponse(reply);
}
return (
<div>
<input value={message} onChange={(e) => setMessage(e.target.value)} />
<button onClick={handleSend}>Send</button>
<p>AI Response: {response}</p>
</div>
);
}
- Có thể tạo chatbot hỗ trợ khách hàng, học ngôn ngữ, hoặc tự động hóa hội thoại.
- Hữu ích cho ecommerce, SaaS, hoặc nền tảng giáo dục.
51. React với Progressive Image Loading: Làm sao tải ảnh nhanh hơn?
Progressive Image Loading giúp hiển thị ảnh mờ trước khi tải ảnh đầy đủ, cải thiện UX trên kết nối chậm.
import { useState } from "react";
function ProgressiveImage({ lowResSrc, highResSrc }) {
const [loaded, setLoaded] = useState(false);
return (
<div>
<img
src={lowResSrc}
style={{ filter: loaded ? "none" : "blur(10px)", transition: "0.5s" }}
/>
<img
src={highResSrc}
onLoad={() => setLoaded(true)}
style={{ position: "absolute", opacity: loaded ? 1 : 0, transition: "0.5s" }}
/>
</div>
);
}
- Cải thiện thời gian tải trang và trải nghiệm người dùng.
- Hữu ích cho website ảnh, ecommerce, hoặc mạng xã hội.
52. React với Web Workers: Làm sao xử lý tác vụ nặng mà không làm chậm UI?
Web Workers giúp chạy tác vụ nặng trên một luồng riêng biệt, tránh làm giật lag giao diện chính của React.
Tạo Web Worker
// worker.js
self.onmessage = function (event) {
const result = event.data.num * 2;
self.postMessage(result);
};
Sử dụng Web Worker trong React
function App() {
const [result, setResult] = React.useState(null);
React.useEffect(() => {
const worker = new Worker(new URL("./worker.js", import.meta.url));
worker.postMessage({ num: 5 });
worker.onmessage = (event) => {
setResult(event.data);
worker.terminate();
};
}, []);
return <p>Result: {result}</p>;
}
- Hữu ích cho xử lý dữ liệu lớn, tính toán phức tạp, AI, hoặc mã hóa.
- Giữ cho giao diện React luôn mượt mà ngay cả khi chạy thuật toán nặng.
53. React với Web Audio API: Làm sao xử lý âm thanh trong trình duyệt?
Web Audio API cho phép React tạo, xử lý và phân tích âm thanh trong thời gian thực.
async function playSound() {
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const oscillator = audioContext.createOscillator();
oscillator.type = "sine";
oscillator.frequency.setValueAtTime(440, audioContext.currentTime); // 440 Hz = nốt A4
oscillator.connect(audioContext.destination);
oscillator.start();
oscillator.stop(audioContext.currentTime + 1); // Dừng sau 1 giây
}
function App() {
return <button onClick={playSound}>Play Sound</button>;
}
- Dùng để tạo hiệu ứng âm thanh, nhạc cụ ảo, hoặc ứng dụng xử lý âm thanh.
- Có thể phân tích âm thanh trong microphone, lọc tạp âm, hoặc làm equalizer.
54. React với IndexedDB: Làm sao lưu trữ dữ liệu lớn trên trình duyệt?
IndexedDB giúp lưu trữ dữ liệu có cấu trúc (như database) trên trình duyệt mà không bị giới hạn dung lượng như localStorage.
const dbPromise = indexedDB.open("myDatabase", 1);
dbPromise.onupgradeneeded = function (event) {
const db = event.target.result;
db.createObjectStore("users", { keyPath: "id" });
};
async function addUser(user) {
const db = (await dbPromise).result;
const tx = db.transaction("users", "readwrite");
tx.objectStore("users").add(user);
}
- Hữu ích cho Progressive Web Apps (PWA), cache dữ liệu offline.
- Không giới hạn dung lượng nhỏ như
localStoragehoặcsessionStorage.
55. React với OffscreenCanvas: Làm sao render đồ họa mà không làm chậm UI?
OffscreenCanvas giúp render đồ họa phức tạp trong Web Workers để tránh làm lag giao diện chính.
const canvas = new OffscreenCanvas(200, 200);
const ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 100, 100);
- Hữu ích cho ứng dụng vẽ, mô phỏng vật lý, hoặc xử lý đồ họa nặng.
- Giữ cho React UI mượt mà ngay cả khi có animation hoặc hình ảnh phức tạp.
56. React với Web NFC API: Làm sao đọc/ghi dữ liệu từ thẻ NFC?
Web NFC API cho phép React giao tiếp với thẻ NFC trên trình duyệt hỗ trợ.
async function readNFC() {
const ndef = new NDEFReader();
await ndef.scan();
ndef.onreading = (event) => {
const decoder = new TextDecoder();
console.log("NFC Data:", decoder.decode(event.message.records[0].data));
};
}
function App() {
return <button onClick={readNFC}>Scan NFC</button>;
}
- Hữu ích cho thanh toán điện tử, smart card, hoặc IoT.
- Có thể dùng để xác thực người dùng không cần mật khẩu.
57. React với Motion Sensors API: Làm sao lấy dữ liệu từ cảm biến gia tốc?
Motion Sensors API cho phép React đọc dữ liệu từ gia tốc kế (accelerometer) hoặc con quay hồi chuyển (gyroscope).
const sensor = new Accelerometer();
sensor.onreading = () => {
console.log(`X: ${sensor.x}, Y: ${sensor.y}, Z: ${sensor.z}`);
};
sensor.start();
- Hữu ích cho ứng dụng AR/VR, game mobile, hoặc điều khiển bằng cử chỉ.
- Có thể dùng để phát hiện chuyển động điện thoại, đo tốc độ di chuyển.
58. React với Face Detection API: Làm sao nhận diện khuôn mặt trong React?
React có thể dùng Face Detection API hoặc TensorFlow.js để nhận diện khuôn mặt trong video.
async function detectFace() {
const stream = await navigator.mediaDevices.getUserMedia({ video: true });
document.getElementById("video").srcObject = stream;
const faceDetector = new FaceDetector();
setInterval(async () => {
const faces = await faceDetector.detect(document.getElementById("video"));
console.log("Faces detected:", faces.length);
}, 500);
}
function App() {
return <button onClick={detectFace}>Start Face Detection</button>;
}
- Hữu ích cho hệ thống điểm danh bằng khuôn mặt, bảo mật AI.
- Có thể dùng trong game hoặc hiệu ứng AR trên trình duyệt.
59. React với Text-to-Speech API: Làm sao tạo trợ lý giọng nói?
Text-to-Speech API giúp React tạo giọng nói AI trực tiếp trên trình duyệt.
function speak(text) {
const speech = new SpeechSynthesisUtterance(text);
speechSynthesis.speak(speech);
}
function App() {
return <button onClick={() => speak("Hello, world!")}>Speak</button>;
}
- Hữu ích cho chatbot, trợ lý ảo, hoặc ứng dụng hỗ trợ người khiếm thị.
- Có thể thay đổi giọng nói, tốc độ đọc, và ngữ điệu.
60. React với Speech Recognition API: Làm sao nhận diện giọng nói?
Speech Recognition API giúp nhận diện giọng nói để điều khiển ứng dụng React bằng lệnh thoại.
const recognition = new window.SpeechRecognition();
recognition.onresult = (event) => {
console.log("User said:", event.results[0][0].transcript);
};
function startListening() {
recognition.start();
}
function App() {
return <button onClick={startListening}>Start Listening</button>;
}
- Hữu ích cho trợ lý ảo, chatbot AI, hoặc điều khiển không cần bàn phím.
- Có thể kết hợp với AI để phân tích giọng nói và hiểu ngữ cảnh.
61. React với WebSockets + AI: Làm sao tạo chatbot AI realtime?
Kết hợp WebSockets và AI để xây dựng chatbot hỗ trợ người dùng theo thời gian thực.
const socket = new WebSocket("wss://chatbot.example.com");
socket.onmessage = (event) => {
console.log("AI Response:", event.data);
};
function sendMessage(message) {
socket.send(JSON.stringify({ text: message }));
}
function Chat() {
const [message, setMessage] = React.useState("");
return (
<div>
<input value={message} onChange={(e) => setMessage(e.target.value)} />
<button onClick={() => sendMessage(message)}>Send</button>
</div>
);
}
- Chatbot phản hồi ngay lập tức mà không cần polling HTTP.
- Hữu ích cho customer support AI, tự động hóa hội thoại.
62. React với TensorFlow.js: Làm sao chạy AI ngay trên trình duyệt?
TensorFlow.js giúp React chạy Machine Learning model trực tiếp trên browser mà không cần backend.
Tải model đã huấn luyện
import * as tf from "@tensorflow/tfjs";
async function loadModel() {
const model = await tf.loadLayersModel("/model.json");
return model;
}
Dự đoán dữ liệu
async function predict(inputData) {
const model = await loadModel();
const tensor = tf.tensor2d([inputData]);
const prediction = model.predict(tensor);
console.log(await prediction.data());
}
Gọi dự đoán trong React
function App() {
return <button onClick={() => predict([0.5, 0.2])}>Predict</button>;
}
- Hữu ích cho nhận diện hình ảnh, phân loại văn bản, hoặc dự đoán dữ liệu.
- Không cần gửi request đến server AI, giúp bảo vệ dữ liệu người dùng.
63. React với D3.js: Làm sao tạo biểu đồ tương tác?
D3.js giúp React tạo các biểu đồ động và trực quan hóa dữ liệu phức tạp.
Tạo biểu đồ cột
import * as d3 from "d3";
import { useEffect } from "react";
function BarChart({ data }) {
useEffect(() => {
const svg = d3.select("#chart").attr("width", 500).attr("height", 300);
svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", (_, i) => i * 50)
.attr("y", d => 300 - d)
.attr("width", 40)
.attr("height", d => d)
.attr("fill", "blue");
}, [data]);
return <svg id="chart"></svg>;
}
function App() {
return <BarChart data={[100, 200, 150, 250]} />;
}
- D3.js giúp tạo biểu đồ động, cập nhật dữ liệu realtime dễ dàng.
- Hữu ích cho dashboard, báo cáo dữ liệu, hoặc trực quan hóa dữ liệu lớn.
64. React với Next.js Middleware: Làm sao tối ưu SEO và bảo mật?
Middleware trong Next.js giúp kiểm soát request trước khi vào page hoặc API routes.
Chặn người dùng chưa đăng nhập
import { NextResponse } from "next/server";
export function middleware(req) {
const token = req.cookies.get("auth");
if (!token) {
return NextResponse.redirect("/login");
}
return NextResponse.next();
}
export const config = {
matcher: "/dashboard/:path*",
};
- Hữu ích cho bảo mật, A/B testing, hoặc redirect người dùng dựa trên điều kiện.
- Chạy ở mức server, không làm chậm tốc độ tải trang.
65. React với WebGPU: Làm sao render đồ họa nhanh hơn WebGL?
WebGPU là API đồ họa thế hệ mới, nhanh hơn WebGL, giúp tăng hiệu suất render trong game hoặc AI.
Khởi tạo WebGPU
async function initWebGPU() {
if (!navigator.gpu) {
console.error("WebGPU is not supported!");
return;
}
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
console.log("WebGPU initialized:", device);
}
function App() {
return <button onClick={initWebGPU}>Initialize WebGPU</button>;
}
- Nhanh hơn WebGL, hỗ trợ đồ họa 3D và AI trên trình duyệt.
- Hữu ích cho game engine, mô phỏng vật lý, hoặc AI tăng tốc GPU.
66. React với Blockchain: Làm sao kết nối React với smart contract?
Web3.js hoặc Ethers.js giúp React tương tác với blockchain, gửi giao dịch, và đọc dữ liệu từ smart contract.
Kết nối với ví MetaMask
import { ethers } from "ethers";
async function connectWallet() {
if (!window.ethereum) return alert("MetaMask not installed!");
const provider = new ethers.providers.Web3Provider(window.ethereum);
await provider.send("eth_requestAccounts", []);
const signer = provider.getSigner();
console.log(await signer.getAddress());
}
function App() {
return <button onClick={connectWallet}>Connect Wallet</button>;
}
- Hữu ích cho NFT marketplace, DeFi app, hoặc DAO voting.
- Có thể gửi token, tương tác với smart contract từ React.
67. React với IoT: Làm sao kết nối React với thiết bị thông minh?
React có thể kết nối với thiết bị IoT qua MQTT để nhận và gửi dữ liệu cảm biến.
Kết nối MQTT
import mqtt from "mqtt";
const client = mqtt.connect("ws://broker.hivemq.com:8000/mqtt");
client.on("connect", () => {
console.log("Connected to MQTT Broker");
client.subscribe("home/temperature");
});
client.on("message", (topic, message) => {
console.log(`Received: ${message.toString()}`);
});
- Hữu ích cho nhà thông minh, cảm biến IoT, hoặc tự động hóa công nghiệp.
- Có thể điều khiển đèn, máy lạnh, hoặc theo dõi nhiệt độ từ React.
68. React với WebUSB: Làm sao kết nối thiết bị USB từ trình duyệt?
WebUSB API cho phép React giao tiếp với thiết bị USB trực tiếp mà không cần cài driver.
Kết nối thiết bị USB
async function connectUSB() {
const device = await navigator.usb.requestDevice({ filters: [] });
await device.open();
console.log("Connected to USB Device:", device);
}
function App() {
return <button onClick={connectUSB}>Connect USB</button>;
}
- Hữu ích cho máy in, thiết bị đo lường, hoặc CNC.
- Có thể truyền dữ liệu trực tiếp đến thiết bị USB từ React.
69. React với WebHID: Làm sao kết nối tay cầm chơi game hoặc bàn phím custom?
WebHID API cho phép React giao tiếp với thiết bị HID như joystick, gamepad, hoặc bàn phím tùy chỉnh.
Nhận dữ liệu từ HID
async function connectHID() {
const devices = await navigator.hid.requestDevice({ filters: [] });
if (devices.length > 0) {
const device = devices[0];
await device.open();
console.log("Connected to HID device:", device);
}
}
function App() {
return <button onClick={connectHID}>Connect HID Device</button>;
}
- Hữu ích cho game controller, máy quét mã vạch, hoặc keyboard custom.
- Có thể lập trình macro hoặc tùy chỉnh phím từ React.
70. React với Gesture Recognition: Làm sao điều khiển UI bằng cử chỉ?
React có thể dùng TensorFlow.js để nhận diện cử chỉ bàn tay và điều khiển UI.
Nhận diện bàn tay với MediaPipe
import * as handpose from "@tensorflow-models/handpose";
import * as tf from "@tensorflow/tfjs";
async function detectHand() {
const video = document.getElementById("video");
const model = await handpose.load();
setInterval(async () => {
const predictions = await model.estimateHands(video);
if (predictions.length > 0) {
console.log("Hand detected:", predictions[0].landmarks);
}
}, 500);
}
function App() {
return <button onClick={detectHand}>Start Hand Detection</button>;
}
- Có thể dùng để điều khiển UI không cần chuột hoặc bàn phím.
- Hữu ích cho AR, game, hoặc hỗ trợ người khuyết tật.
71. React với Web Speech API: Làm sao tạo lệnh thoại để điều khiển UI?
Web Speech API cho phép nhận diện giọng nói để thực hiện các thao tác trên UI như tìm kiếm hoặc điều hướng.
Nhận diện giọng nói
const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
recognition.lang = "en-US";
recognition.onresult = (event) => {
const transcript = event.results[0][0].transcript;
console.log("User said:", transcript);
};
function startListening() {
recognition.start();
}
function App() {
return <button onClick={startListening}>Start Voice Command</button>;
}
- Hữu ích cho trợ lý ảo, điều khiển UI không cần chạm, hoặc tìm kiếm bằng giọng nói.
- Có thể kết hợp với AI để hiểu ngữ cảnh và phản hồi thông minh hơn.
72. React với WebRTC: Làm sao tạo ứng dụng gọi video P2P?
WebRTC giúp tạo kết nối video giữa hai trình duyệt mà không cần server trung gian.
Tạo kết nối WebRTC
const peer = new RTCPeerConnection();
navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then((stream) => {
document.getElementById("localVideo").srcObject = stream;
stream.getTracks().forEach((track) => peer.addTrack(track, stream));
});
peer.ontrack = (event) => {
document.getElementById("remoteVideo").srcObject = event.streams[0];
};
function App() {
return (
<div>
<video id="localVideo" autoPlay muted></video>
<video id="remoteVideo" autoPlay></video>
</div>
);
}
- Hữu ích cho gọi video, chia sẻ màn hình, hoặc truyền dữ liệu P2P.
- Không cần backend để xử lý media, giảm độ trễ kết nối.
73. React với WebVR & AR: Làm sao tạo trải nghiệm thực tế ảo (VR) và tăng cường (AR)?
WebXR API giúp hiển thị nội dung AR/VR trên trình duyệt mà không cần cài đặt phần mềm bổ sung.
Tạo môi trường VR với React Three Fiber
import { Canvas } from "@react-three/fiber";
import { VRButton, XR } from "@react-three/xr";
function Scene() {
return (
<Canvas>
<XR>
<VRButton />
<mesh>
<boxGeometry args={[1, 1, 1]} />
<meshStandardMaterial color="red" />
</mesh>
</XR>
</Canvas>
);
}
function App() {
return <Scene />;
}
- Hữu ích cho game, mô phỏng 3D, hoặc hướng dẫn sản phẩm bằng AR.
- Có thể dùng WebXR để hỗ trợ kính VR như Oculus hoặc HTC Vive.
74. React với FingerprintJS: Làm sao xác định người dùng mà không cần cookies?
FingerprintJS giúp nhận diện người dùng bằng dấu vết trình duyệt mà không cần lưu cookie.
Lấy fingerprint của người dùng
import FingerprintJS from "@fingerprintjs/fingerprintjs";
async function getFingerprint() {
const fp = await FingerprintJS.load();
const result = await fp.get();
console.log("User Fingerprint:", result.visitorId);
}
function App() {
return <button onClick={getFingerprint}>Get User ID</button>;
}
- Hữu ích cho bảo mật, chống gian lận, hoặc phân tích hành vi người dùng.
- Không phụ thuộc vào cookies hoặc localStorage.
75. React với Google Maps API: Làm sao hiển thị bản đồ tương tác?
Google Maps API giúp React nhúng bản đồ và hiển thị vị trí hoặc tuyến đường.
Nhúng Google Maps vào React
function loadMap() {
new google.maps.Map(document.getElementById("map"), {
center: { lat: 10.7769, lng: 106.7009 },
zoom: 12,
});
}
function App() {
return (
<div>
<button onClick={loadMap}>Load Map</button>
<div id="map" style={{ width: "100%", height: "400px" }}></div>
</div>
);
}
- Hữu ích cho ứng dụng chỉ đường, đặt xe, hoặc tìm kiếm địa điểm.
- Có thể kết hợp với GPS để theo dõi vị trí người dùng.
76. React với Barcode Scanner: Làm sao quét mã vạch trong trình duyệt?
Barcode Scanner API giúp React đọc mã QR hoặc mã vạch từ camera.
Quét mã vạch bằng ZXing
import { BrowserMultiFormatReader } from "@zxing/library";
async function scanBarcode() {
const codeReader = new BrowserMultiFormatReader();
const result = await codeReader.decodeFromInputVideoDevice(undefined, "video");
console.log("Barcode Scanned:", result.text);
}
function App() {
return (
<div>
<button onClick={scanBarcode}>Scan Barcode</button>
<video id="video" width="300" height="200"></video>
</div>
);
}
- Hữu ích cho thanh toán, quản lý kho, hoặc kiểm tra sản phẩm.
- Có thể dùng camera điện thoại để quét mã vạch ngay trên web.
77. React với WebSockets và Redux: Làm sao cập nhật dữ liệu realtime?
WebSockets giúp cập nhật dữ liệu realtime mà không cần polling HTTP.
Kết nối Redux với WebSockets
import { createStore } from "redux";
const initialState = { message: "" };
function reducer(state = initialState, action) {
if (action.type === "NEW_MESSAGE") {
return { ...state, message: action.payload };
}
return state;
}
const store = createStore(reducer);
const socket = new WebSocket("wss://example.com");
socket.onmessage = (event) => {
store.dispatch({ type: "NEW_MESSAGE", payload: event.data });
};
function Chat() {
const message = store.getState().message;
return <p>Latest Message: {message}</p>;
}
- Hữu ích cho ứng dụng chat, thông báo realtime, hoặc bảng giá chứng khoán.
- Kết hợp với Redux giúp quản lý state tốt hơn.
78. React với Web Push Notifications: Làm sao gửi thông báo đến trình duyệt?
Web Push API giúp React gửi thông báo ngay cả khi ứng dụng không mở.
Đăng ký Web Push
async function subscribeToNotifications() {
const registration = await navigator.serviceWorker.register("/sw.js");
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: "YOUR_PUBLIC_VAPID_KEY",
});
console.log("Subscription:", JSON.stringify(subscription));
}
function App() {
return <button onClick={subscribeToNotifications}>Subscribe to Push</button>;
}
- Hữu ích cho thông báo đơn hàng, tin tức mới, hoặc nhắc nhở lịch hẹn.
- Có thể gửi thông báo ngay cả khi trình duyệt đang đóng.
79. React với Dark Mode: Làm sao thay đổi theme động?
CSS Variables giúp thay đổi theme Dark/Light một cách mượt mà.
CSS Variables cho Dark Mode
:root {
--bg-color: white;
--text-color: black;
}
.dark-mode {
--bg-color: black;
--text-color: white;
}
Chuyển đổi Dark Mode trong React
function toggleTheme() {
document.body.classList.toggle("dark-mode");
}
function App() {
return <button onClick={toggleTheme}>Toggle Dark Mode</button>;
}
- Hữu ích cho UX, giúp người dùng có trải nghiệm tốt hơn ban đêm.
- Có thể lưu trạng thái theme vào localStorage để ghi nhớ lần sau.
80. React với Web Animations API: Làm sao tạo animation hiệu suất cao?
Web Animations API giúp React tạo animation mượt mà mà không cần thư viện bên ngoài như GSAP hoặc Framer Motion.
Tạo animation bằng Web Animations API
function animateBox() {
const box = document.getElementById("box");
box.animate(
[{ transform: "translateX(0px)" }, { transform: "translateX(200px)" }],
{ duration: 1000, iterations: 1 }
);
}
function App() {
return (
<div>
<button onClick={animateBox}>Animate</button>
<div id="box" style={{ width: 100, height: 100, background: "blue" }}></div>
</div>
);
}
- Hiệu suất cao hơn CSS animations, có thể điều khiển bằng JavaScript.
- Hữu ích cho UI động, animation tương tác, hoặc hiển thị dữ liệu sinh động.
81. React với Web MIDI API: Làm sao kết nối nhạc cụ MIDI?
Web MIDI API giúp React giao tiếp với nhạc cụ điện tử như keyboard MIDI hoặc synths.
Nhận dữ liệu từ MIDI
async function connectMIDI() {
const access = await navigator.requestMIDIAccess();
const inputs = access.inputs.values();
for (let input of inputs) {
input.onmidimessage = (event) => {
console.log("MIDI Data:", event.data);
};
}
}
function App() {
return <button onClick={connectMIDI}>Connect MIDI</button>;
}
- Hữu ích cho ứng dụng âm nhạc, DJ software, hoặc phần mềm sáng tác nhạc.
- Có thể tạo ứng dụng hiển thị sheet nhạc hoặc điều khiển synths.
82. React với WebGL Shaders: Làm sao tạo hiệu ứng đồ họa nâng cao?
WebGL Shaders giúp tạo hiệu ứng đồ họa như đổ bóng, phản chiếu, hoặc ánh sáng phức tạp.
Tạo WebGL context
const canvas = document.getElementById("glCanvas");
const gl = canvas.getContext("webgl");
if (!gl) {
console.error("WebGL not supported");
}
function App() {
return <canvas id="glCanvas" width="500" height="500"></canvas>;
}
- Hữu ích cho game engine, mô phỏng vật lý, hoặc ứng dụng 3D trong React.
- Có thể kết hợp với Three.js hoặc Babylon.js để tạo cảnh phức tạp hơn.
83. React với PWA Offline Mode: Làm sao lưu trang để chạy khi không có mạng?
PWA giúp React chạy offline bằng cách caching dữ liệu và tài nguyên với Service Worker.
Cấu hình Service Worker
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open("app-cache").then((cache) => {
return cache.addAll(["/", "/index.html", "/styles.css", "/app.js"]);
})
);
});
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/sw.js");
}
function App() {
return <h1>PWA Offline Mode</h1>;
}
- Giúp ứng dụng hoạt động ngay cả khi mất kết nối mạng.
- Hữu ích cho ứng dụng tin tức, e-commerce, hoặc quản lý công việc.
84. React với WebUSB HID: Làm sao điều khiển tay cầm chơi game?
WebUSB HID API giúp React giao tiếp với tay cầm chơi game, bàn phím cơ, hoặc thiết bị HID tùy chỉnh.
Nhận dữ liệu từ tay cầm chơi game
async function connectGamepad() {
const devices = await navigator.hid.requestDevice({ filters: [] });
if (devices.length > 0) {
const device = devices[0];
await device.open();
console.log("Gamepad Connected:", device);
}
}
function App() {
return <button onClick={connectGamepad}>Connect Gamepad</button>;
}
- Hữu ích cho game HTML5, trình điều khiển tùy chỉnh, hoặc máy quét mã vạch.
- Có thể lập trình phím macro hoặc điều khiển robot bằng HID device.
85. React với WebGPU Compute: Làm sao tăng tốc AI trên trình duyệt?
WebGPU Compute giúp chạy tác vụ xử lý nặng như AI, Machine Learning, hoặc mô phỏng vật lý trên GPU.
Khởi tạo WebGPU Compute
async function runComputeShader() {
if (!navigator.gpu) {
console.error("WebGPU is not supported!");
return;
}
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
console.log("WebGPU Compute Initialized:", device);
}
function App() {
return <button onClick={runComputeShader}>Run WebGPU Compute</button>;
}
- Hữu ích cho AI, deep learning, hoặc xử lý đồ họa nâng cao.
- Nhanh hơn WebGL, có thể tận dụng GPU để tăng tốc tính toán.
86. React với WebHID API: Làm sao lập trình bàn phím cơ tùy chỉnh?
WebHID API cho phép React đọc và gửi dữ liệu đến bàn phím cơ có thể lập trình.
Kết nối bàn phím HID
async function connectKeyboard() {
const devices = await navigator.hid.requestDevice({ filters: [] });
if (devices.length > 0) {
const device = devices[0];
await device.open();
console.log("Keyboard Connected:", device);
}
}
function App() {
return <button onClick={connectKeyboard}>Connect Keyboard</button>;
}
- Hữu ích cho gamer, lập trình viên muốn tùy chỉnh macro.
- Có thể tạo phần mềm điều khiển ánh sáng LED trên bàn phím cơ.
87. React với Web Serial API: Làm sao kết nối Arduino với React?
Web Serial API cho phép React giao tiếp với board Arduino hoặc thiết bị nối tiếp qua USB.
Gửi lệnh đến Arduino
async function connectArduino() {
const port = await navigator.serial.requestPort();
await port.open({ baudRate: 9600 });
const writer = port.writable.getWriter();
await writer.write(new TextEncoder().encode("LED_ON"));
writer.releaseLock();
}
function App() {
return <button onClick={connectArduino}>Turn On LED</button>;
}
- Hữu ích cho dự án IoT, điều khiển phần cứng, hoặc robot.
- Có thể gửi dữ liệu cảm biến từ Arduino đến React để hiển thị.
88. React với Web Sockets và AI: Làm sao tạo AI chatbot realtime?
Web Sockets giúp React gửi và nhận tin nhắn AI ngay lập tức mà không cần polling HTTP.
Gửi tin nhắn đến AI server
const socket = new WebSocket("wss://ai-chatbot.example.com");
socket.onmessage = (event) => {
console.log("AI Response:", event.data);
};
function sendMessage(message) {
socket.send(JSON.stringify({ text: message }));
}
function Chat() {
const [message, setMessage] = React.useState("");
return (
<div>
<input value={message} onChange={(e) => setMessage(e.target.value)} />
<button onClick={() => sendMessage(message)}>Send</button>
</div>
);
}
- Hữu ích cho AI chatbot hỗ trợ khách hàng, tự động hóa hội thoại.
- Có thể tích hợp GPT-4 hoặc AI tùy chỉnh để hiểu ngữ cảnh tốt hơn.
89. React với WebRTC Data Channel: Làm sao gửi dữ liệu P2P mà không cần server?
WebRTC Data Channel cho phép React gửi dữ liệu giữa hai trình duyệt mà không cần server trung gian, giúp giảm độ trễ và bảo mật hơn.
Tạo kết nối WebRTC Data Channel
const peer = new RTCPeerConnection();
const dataChannel = peer.createDataChannel("chat");
dataChannel.onopen = () => console.log("Data Channel Opened");
dataChannel.onmessage = (event) => console.log("Received:", event.data);
function sendMessage(message) {
dataChannel.send(message);
}
function App() {
return <button onClick={() => sendMessage("Hello Peer!")}>Send P2P Message</button>;
}
- Hữu ích cho chat P2P, chia sẻ file không cần server, hoặc ứng dụng phi tập trung (DApp).
- Giảm chi phí server vì dữ liệu truyền trực tiếp giữa hai client.
90. React với WebRTC Screen Sharing: Làm sao chia sẻ màn hình?
WebRTC hỗ trợ chia sẻ màn hình trực tiếp từ trình duyệt, giúp tạo ứng dụng gọi video, livestream, hoặc hỗ trợ kỹ thuật.
Lấy màn hình chia sẻ
async function shareScreen() {
const stream = await navigator.mediaDevices.getDisplayMedia({ video: true });
document.getElementById("screen").srcObject = stream;
}
function App() {
return (
<div>
<button onClick={shareScreen}>Share Screen</button>
<video id="screen" autoPlay></video>
</div>
);
}
- Hữu ích cho hội nghị trực tuyến, livestream, hoặc hướng dẫn từ xa.
- Có thể kết hợp với WebRTC để truyền màn hình đến người dùng khác.
91. React với WebGPU Compute Shaders: Làm sao tăng tốc xử lý đồ họa AI?
WebGPU hỗ trợ Compute Shaders để tăng tốc tính toán đồ họa và AI ngay trên GPU.
Khởi tạo Compute Shaders
async function runComputeShader() {
if (!navigator.gpu) {
console.error("WebGPU is not supported!");
return;
}
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
console.log("WebGPU Compute Shader Initialized:", device);
}
function App() {
return <button onClick={runComputeShader}>Run Compute Shader</button>;
}
- Hữu ích cho AI, deep learning, hoặc xử lý đồ họa nâng cao.
- Nhanh hơn WebGL và có thể tận dụng GPU để tăng tốc tính toán.
92. React với WebOTP API: Làm sao tự động điền OTP trên trình duyệt?
WebOTP API cho phép React nhận OTP SMS và tự động điền vào form xác thực.
Lấy OTP tự động
async function getOTP() {
if (!window.OTPCredential) return;
const otp = await navigator.credentials.get({ otp: { transport: ["sms"] } });
document.getElementById("otp").value = otp.code;
}
function App() {
return (
<div>
<input id="otp" placeholder="Enter OTP" />
<button onClick={getOTP}>Get OTP</button>
</div>
);
}
- Hữu ích cho đăng nhập bảo mật, giảm thao tác nhập OTP thủ công.
- Hoạt động trên trình duyệt Chrome và Android.
93. React với Web Speech Synthesis API: Làm sao tạo trợ lý AI nói chuyện?
Web Speech Synthesis API giúp React tạo giọng nói AI trực tiếp trên trình duyệt.
Phát giọng nói AI
function speak(text) {
const speech = new SpeechSynthesisUtterance(text);
speechSynthesis.speak(speech);
}
function App() {
return <button onClick={() => speak("Hello, how can I assist you?")}>Speak</button>;
}
- Hữu ích cho trợ lý ảo, AI chatbot, hoặc ứng dụng hỗ trợ người khiếm thị.
- Có thể điều chỉnh giọng, tốc độ, và ngữ điệu của AI.
94. React với Gesture Detection API: Làm sao nhận diện cử chỉ bàn tay?
TensorFlow.js giúp nhận diện cử chỉ tay để điều khiển UI mà không cần chạm vào màn hình.
Nhận diện bàn tay bằng MediaPipe
import * as handpose from "@tensorflow-models/handpose";
import * as tf from "@tensorflow/tfjs";
async function detectHand() {
const video = document.getElementById("video");
const model = await handpose.load();
setInterval(async () => {
const predictions = await model.estimateHands(video);
if (predictions.length > 0) {
console.log("Hand detected:", predictions[0].landmarks);
}
}, 500);
}
function App() {
return (
<div>
<video id="video" autoPlay></video>
<button onClick={detectHand}>Start Hand Detection</button>
</div>
);
}
- Hữu ích cho UI không cần chạm, game VR, hoặc hỗ trợ người khuyết tật.
- Có thể dùng để nhận diện số đếm, điều khiển cử chỉ tay.
95. React với Blockchain Smart Contracts: Làm sao kết nối với Ethereum?
Ethers.js giúp React kết nối với smart contract Ethereum để gửi giao dịch hoặc đọc dữ liệu.
Kết nối với MetaMask và gửi giao dịch
import { ethers } from "ethers";
async function sendTransaction() {
if (!window.ethereum) return alert("MetaMask not installed!");
const provider = new ethers.providers.Web3Provider(window.ethereum);
await provider.send("eth_requestAccounts", []);
const signer = provider.getSigner();
const tx = await signer.sendTransaction({
to: "0xReceiverAddress",
value: ethers.utils.parseEther("0.01"),
});
console.log("Transaction Sent:", tx.hash);
}
function App() {
return <button onClick={sendTransaction}>Send ETH</button>;
}
- Hữu ích cho DeFi, NFT marketplace, hoặc DAO voting.
- Có thể đọc dữ liệu từ smart contract như số dư ví hoặc token.
96. React với AI Image Generation: Làm sao tạo ảnh bằng AI ngay trên trình duyệt?
TensorFlow.js giúp React tạo ảnh AI mà không cần server.
Tạo ảnh với GAN Model
import * as tf from "@tensorflow/tfjs";
async function generateImage() {
const model = await tf.loadLayersModel("/gan_model.json");
const noise = tf.randomNormal([1, 100]);
const generatedImage = model.predict(noise);
document.getElementById("canvas").getContext("2d").putImageData(generatedImage, 0, 0);
}
function App() {
return (
<div>
<canvas id="canvas"></canvas>
<button onClick={generateImage}>Generate Image</button>
</div>
);
}
- Hữu ích cho AI Art, tạo hình ảnh từ văn bản (Text-to-Image).
- Có thể kết hợp với OpenAI DALL·E hoặc Stable Diffusion.
97. React với Web NFC API: Làm sao quét và ghi dữ liệu NFC?
Web NFC API giúp React giao tiếp với thẻ NFC để đọc hoặc ghi dữ liệu.
Quét thẻ NFC
async function readNFC() {
const ndef = new NDEFReader();
await ndef.scan();
ndef.onreading = (event) => {
const decoder = new TextDecoder();
console.log("NFC Data:", decoder.decode(event.message.records[0].data));
};
}
function App() {
return <button onClick={readNFC}>Scan NFC</button>;
}
- Hữu ích cho thanh toán, quản lý kho, hoặc smart access cards.
- Có thể ghi dữ liệu vào thẻ NFC để lưu thông tin.
98. React với Web Assembly (WASM): Làm sao chạy code C++ trong React?
WebAssembly (WASM) giúp React chạy code C++, Rust, hoặc Go ngay trên trình duyệt để tăng hiệu suất.
Viết hàm C++ và biên dịch sang WebAssembly
cppSao chépChỉnh sửa// add.cpp
extern "C" {
int add(int a, int b) {
return a + b;
}
}
Biên dịch thành WebAssembly:
shSao chépChỉnh sửaemcc add.cpp -s WASM=1 -o add.wasm
Sử dụng WebAssembly trong React
javascriptSao chépChỉnh sửaasync function loadWasm() {
const response = await fetch("add.wasm");
const buffer = await response.arrayBuffer();
const module = await WebAssembly.instantiate(buffer);
console.log("Result:", module.instance.exports.add(5, 3));
}
jsxSao chépChỉnh sửafunction App() {
return <button onClick={loadWasm}>Run WASM</button>;
}
- Hữu ích cho xử lý số liệu, AI, game engine trong React.
- Nhanh hơn JavaScript khi chạy thuật toán phức tạp.
99. React với Web Bluetooth API: Làm sao kết nối thiết bị thông minh?
Web Bluetooth API giúp React giao tiếp với thiết bị IoT như đèn thông minh, cảm biến nhiệt độ.
Kết nối Bluetooth
javascriptSao chépChỉnh sửaasync function connectBluetooth() {
const device = await navigator.bluetooth.requestDevice({
acceptAllDevices: true,
optionalServices: ["battery_service"],
});
const server = await device.gatt.connect();
const service = await server.getPrimaryService("battery_service");
const characteristic = await service.getCharacteristic("battery_level");
const value = await characteristic.readValue();
console.log(`Battery level: ${value.getUint8(0)}%`);
}
jsxSao chépChỉnh sửafunction App() {
return <button onClick={connectBluetooth}>Connect Bluetooth</button>;
}
- Hữu ích cho smart home, fitness tracker, hoặc điều khiển thiết bị IoT.
- Không cần cài đặt phần mềm bên ngoài, chạy trực tiếp trên trình duyệt.
100. React với WebGL Physically-Based Rendering (PBR): Làm sao tạo vật liệu 3D chân thực?
WebGL PBR giúp hiển thị vật liệu chân thực như kim loại, gương phản chiếu trong trình duyệt.
Tạo cảnh WebGL PBR
javascriptSao chépChỉnh sửaimport * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
async function loadScene() {
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
document.body.appendChild(renderer.domElement);
const loader = new GLTFLoader();
const model = await loader.loadAsync("model.glb");
scene.add(model.scene);
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
}
jsxSao chépChỉnh sửafunction App() {
return <button onClick={loadScene}>Load 3D Scene</button>;
}
- Hữu ích cho game, trình xem sản phẩm 3D, hoặc thực tế ảo (VR).
- Có thể kết hợp với WebXR để tạo ứng dụng AR/VR.







-
Tagged flutter, mobile-dev, react-native