Context là một cách để chúng ta truyền props đến các component con mà không cần truyền từ trên xuống dưới theo cấu trúc component.
The Problem with Passing Props
Có thể thấy trong ví dụ bên dưới, để truyền props từ component cha xuống component con thì cần phải thông qua component trung gian là Toolbar.
import React from "react"
function App() {
return <Toolbar theme="dark" />
}
function Toolbar(props) {
return (
<div>
<Button theme={props.theme} />
</div>
)
}
function Button(props) {
return <button>Theme: {props.theme}</button>
}Trong tương lai, có thể có thêm nhiều component trung gian, hoặc cần phải truyền thêm nhiều giá trị vào props. Việc này khiến chúng ta phải chỉnh sửa lại code rất nhiều.
Để props trở nên global và có thể được truy cập bởi tất cả các component, chúng ta cần phải sử dụng context.
Usage
Create the Context
Tạo ra context bằng cách sử dụng hàm createContext như sau:
import React from "react"
const ThemeContext = React.createContext("dark")Đối số của createContext là giá trị mặc định và context cần được đặt ở bên ngoài component.
Provide the Context
Ta dùng component ThemeContext.Provider với thuộc tính value có giá trị là props mà ta muốn truyền các component con.
import React from "react"
const ThemeContext = React.createContext("dark")
function App() {
return (
<ThemeContext.Provider value="light">
<Toolbar />
</ThemeContext.Provider>
)
}Một provider có thể được sử dụng bởi nhiều component, miễn sao tất cả các component đó đều là component con của provider. Nếu component con không tìm thấy bất cứ provider nào, giá trị mặc định ("dark") sẽ được sử dụng.
Use the Context
Để lấy props được truyền từ component cha, ta cần dùng hook useContext. React sẽ tìm provider gần nhất và trích xuất dữ liệu từ đó.
import React, { useContext } from "react"
const ThemeContext = React.createContext("dark")
// App and Toolbar components ...
function Button() {
const theme = useContext(ThemeContext)
return <button>Theme: {theme}</button>
}Có thể thấy, đối số của useContext là một đối tượng context. Giá trị trả về là value của provider.
Info
Các component con sẽ được re-render khi
valuecủa provider thay đổi.
Use Cases for Context
Các trường hợp có thể dùng context để lưu và truyền dữ liệu:
- Theme
- Current account
- Routing
- State management (kết hợp với useReducer).
Trong trường hợp ta truyền dữ liệu vào một parent component chỉ để truyền xuống các child component của nó thì ta không nên dùng context. Thay vào đó, ta nên truyền vào child component có props chứa dữ liệu để parent component có thể render ra1.
Ví dụ:
<Layout posts={posts} />Nếu component Layout không thật sự sử dụng dữ liệu posts thì ta nên truyền vào child component có chứa dữ liệu đó như sau:
<Layout><Posts posts={posts} />Resources
Footnotes
-
xem thêm Passing JSX as Children. ↩