The React Context API is a feature that allows you to share state (data) across multiple components without passing props down manually at every level of the component tree. It simplifies state management, especially in large applications where many components need access to the same data.
const MyContext = React.createContext();
<MyContext.Provider value={someValue}> {children} </MyContext.Provider>
const someValue = useContext(MyContext);
const ThemeContext = React.createContext();
const App = () => { const theme = 'dark'; return ( <ThemeContext.Provider value={theme}> <ChildComponent /> </ThemeContext.Provider> ); };
const ChildComponent = () => { const theme = useContext(ThemeContext); return <div>Current theme: {theme}</div>; };
以上是React 上下文 API 概述的详细内容。更多信息请关注PHP中文网其他相关文章!