Translate

Views

Friday, February 14, 2025

Context React (Cách đơn giản nhất để truyền props trong React)

 Cách đơn giản nhất để truyền props trong React mà không cần truyền qua nhiều cấp là sử dụng Context API. Dưới đây là cách triển khai cực kỳ đơn giản:


🔹 1. Tạo Context

Tạo một file riêng, ví dụ: MyContext.js

jsx
import { createContext, useState } from "react"; export const MyContext = createContext(); export const MyProvider = ({ children }) => { const [message, setMessage] = useState("Hello from Context!"); return ( <MyContext.Provider value={{ message, setMessage }}> {children} </MyContext.Provider> ); };

🔹 2. Bọc App bằng Provider

Mở file app/layout.tsx (nếu dùng Next.js 14 App Router) hoặc index.js (React thường) và bọc toàn bộ ứng dụng bằng MyProvider:

jsx
import { MyProvider } from "./MyContext"; export default function RootLayout({ children }) { return ( <MyProvider> <html lang="en"> <body>{children}</body> </html> </MyProvider> ); }

🔹 3. Sử dụng Context ở Component con

Bất cứ component nào trong cây component đều có thể truy cập message:

jsx
import { useContext } from "react"; import { MyContext } from "./MyContext"; const ChildComponent = () => { const { message, setMessage } = useContext(MyContext); return ( <div> <h1>{message}</h1> <button onClick={() => setMessage("Context đã thay đổi!")}> Thay đổi Context </button> </div> ); }; export default ChildComponent;

Tóm lại:

  1. Tạo Context (MyContext.js)
  2. Bọc ứng dụng bằng Provider (layout.tsx hoặc index.js)
  3. Dùng useContext() để lấy dữ liệu ở bất kỳ component nào

Thế là xong! Không cần truyền props lằng nhằng qua từng component. 🚀

No comments: