useContext เป็น hook ให้เราเข้าถึง context object ใน functional component โดย context จะเป็นวิธีการส่งข้อมูลไปยัง component ที่อยู่ใน tree โดยไม่ต้องส่ง props มาทีละตัว
เข้าใจง่ายๆ ก็คือ อะไรที่อยู่ใต้ context นั้น สามารถเข้าถึงได้โดยไม่ต้องส่ง props ให้แต่ละ component
import React, { useContext } from "react";
const ThemeContext = React.createContext("light");
function ThemeButton() {
const theme = useContext(ThemeContext);
return (
<button
style={{
background: theme === "dark" ? "black" : "white",
color: theme === "dark" ? "white" : "black",
}}
>
Toggle Theme
</button>
);
}
จากตัวอย่างข้างบน เราจะมีการสร้าง context ที่มีชื่อว่า ThemeContext แล้วกำหนดค่าให้เป็น light
จากนั้นเราสร้างตัวแปรชื่อ theme เพื่อรับค่าจาก ThemeContext
โดยใช้ useContext
เสร็จแล้วก็นำไปใช้กับ button