useContext trong React là một hook dùng để truy cập dữ liệu từ Context, mà không cần phải truyền props thủ công qua nhiều cấp component (gọi là props drilling)
import React, { createContext, useContext } from 'react';
// 1. Tạo context
const ThemeContext = createContext();
// 2. Tạo component cha cung cấp context
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
// 3. Ở component con, dùng useContext để lấy giá trị
function Toolbar() {
const theme = useContext(ThemeContext);
return <p>Current theme: {theme}</p>;
}Tuy nhiên, nếu dữ liệu chỉ được dùng trong một vài component nhỏ, hoặc không thường xuyên thay đổi, dùng props hoặc useState là đủ.
Vì nếu dữ liệu thay đổi liên tục, context có thể gây ra re-render toàn bộ cây component, làm giảm hiệu năng.
Mô phỏng cơ chế
// Giả lập React.createContext
function createContext(defaultValue) {
const context = {
value: defaultValue,
Provider({ value, children }) {
context.value = value
return children()
}
}
return context;
}
// Giả lập useContext
function useContext(context) {
return context.value;
}
// Sử dụng
const ThemeContext = createContext('light')
function App() {
return ThemeContext.Provider({
value: 'dark',
children: Toolbar
})
}
function Toolbar() {
return Button()
}
function Button() {
const theme = useContext(ThemeContext)
console.log("Current theme:", theme)
}
App();
// Output: Current theme: darkĐây chỉ là mô phỏng ý tưởng của useContext, React thực tế sẽ còn phải làm các việc như:
- Liên kết context với cây fiber.
- Tự động re-render khi giá trị context thay đổi.
- Xử lý context lồng nhau.
- Chống leak hoặc stale value.