如何使用 useContext React hook

了解 useContext React hook 的用途,以及如何使用它! 如果您對 React hooks 還不熟悉,請先查看我的React hooks 簡介。 在 React 中,我有時會使用一個叫做 useContext 的 hook。 import React, { useContext } from 'react' 這個 hook 與 React Context API 搭配使用。 特別是,這個 hook 允許我們獲取當前的 context 值: const value = useContext(MyContext) 這個值是指最接近的 <MyContext.Provider> 組件。 調用 useContext 還會確保在 context 值發生變化時重新渲染組件。 我建議您閱讀我的Context API 教程以更深入地了解它。