文章目錄
- 前言
- 一、React 19中useContext移除了Provider?
- 二、使用步驟
- 總結
前言
在 React 19 中,useContext 的使用方式有所更新。開發者現在可以直接使用 作為提供者,而不再需要使用 <Context.Provider>。這一變化簡化了代碼結構,提升了開發效率。文章中通過示例代碼展示了如何創建上下文、在子組件中使用 useContext,以及如何通過 useState 更新上下文中的值。盡管 useContext 提供了便捷的跨組件數據共享方式,但使用時需注意避免濫用和性能問題。通過合理拆分上下文并結合 TypeScript 和性能優化,可以更好地發揮其優勢。
一、React 19中useContext移除了Provider?
在 React 19 中,你可以將 渲染為提供者,就無需再使用 <Context.Provider> 了:
二、使用步驟
import { createContext, useContext, useState } from "react";interface MyContextType {name: string;setName: (value: string) => void;
}// 創建上下文
const MyContext = createContext<MyContextType>({} as MyContextType);const Son = () => {const name = useContext(MyContext);console.log(name);return <div>Son</div>;
};
// 子組件
const Child = () => {const name = useContext(MyContext);console.log(name);return <div>Child</div>;
};
const App = () => {const [name, setName] = useState("小路");return (<div><button onClick={() => setName("123")}>改變name值</button><MyContext value={{ name, setName }}><Child /><hr /><Son /></MyContext></div>);
};export default App;
總結
useContext 是 React 中一個強大且靈活的 Hook,它通過 Context API 提供了跨組件共享數據的便捷方式。然而,使用時需要謹慎,避免濫用和性能問題。通過合理拆分上下文、結合 TypeScript 和性能優化,可以更好地發揮 useContext 的優勢。