学习React-16-useContext

使用 useContext 的基本概念

useContext 是 React Hooks 的一部分,用于在函数组件中访问 React 的 Context。Context 提供了一种在组件树中共享数据的方式,避免了逐层传递 props 的繁琐。

创建 Context

需要先通过 React.createContext 创建一个 Context 对象,并设置默认值(可选):

javascript 复制代码
const MyContext = React.createContext(defaultValue);

提供 Context 值

在父组件中使用 Context.Provider 包裹子组件,并通过 value 属性传递数据:

javascript 复制代码
<MyContext.Provider value={/* 共享的数据 */}>
  <ChildComponent />
</MyContext.Provider>

在子组件中消费 Context

在函数组件中通过 useContext 直接获取 Context 的值:

javascript 复制代码
const value = useContext(MyContext);

小栗子

以下是一个完整的示例,展示如何创建、提供和使用 Context:

ts 复制代码
import React, {useState, useContext} from 'react'

interface ThemeContextType {
    theme: string
    setTheme: (theme: string) => void
}
// 声明上下文
const MyContext = React.createContext<ThemeContextType>({} as ThemeContextType)

const style = {
    width: '100px',
    height: '100px',
    backgroundColor: 'black',
    marginTop: '10px'
}

const Child = () => {
    const theme = useContext(MyContext)
    return (
        <div>
            子组件
            <button onClick={() => theme.setTheme('dark')}>子组件切换</button>
            <div style={{...style, backgroundColor: theme.theme == 'light'? 'green': 'black'}}>
            
        </div>
        </div>
        
    )
}

const Parent = () => {
    // 使用上下文
    const theme = useContext(MyContext)
    return (
        <div>
            父组件
            <button onClick={() => theme.setTheme('light')}>父组件切换</button>
            <div style={{...style, backgroundColor: theme.theme == 'light'? 'green': 'black'}}></div>
            <Child />
        </div>
    )
}

export const App = () => {
    const [theme, setTheme] = useState('light')
    return (
        <div>
            <button onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}>主题切换</button>
            <MyContext.Provider value={{theme, setTheme}}>
                <Parent />
            </MyContext.Provider>
        </div>
    )
}

export default App

注意:上面的栗子是React18的语法,React19中已经不需要使用Provider。

ts 复制代码
// React 19的语法
<MyContextvalue={{theme, setTheme}}>
      <Parent />
</MyContext>

多 Context 使用

一个组件可以消费多个 Context,只需多次调用 useContext

javascript 复制代码
const user = useContext(UserContext);
const theme = useContext(ThemeContext);

性能优化

避免因不必要的重新渲染导致性能问题,可以将 Context 的值通过 useMemouseState 进行优化:

javascript 复制代码
const [value, setValue] = useState(initialValue);
const memoizedValue = useMemo(() => ({ value, setValue }), [value]);

return (
  <MyContext.Provider value={memoizedValue}>
    {/* 子组件 */}
  </MyContext.Provider>
);

注意事项

  • 默认情况下,useContext 会监听 Context 值的变化,即使父组件使用 React.memoshouldComponentUpdate,子组件仍会重新渲染。
  • 如果 Context 的 value 是一个新对象(如 value={``{ theme }}),每次渲染都会触发子组件更新,应避免直接传递内联对象。
  • 如果重复嵌套使用并且使用的值是相同的则里层的值会覆盖外层的值。
相关推荐
Cutecat_6 分钟前
视频字幕处理工具横向:提取模式 vs 编辑模式,该如何选择
android·前端·ios·语音识别
qq_4221525727 分钟前
PDF 加水印工具怎么选?2026 年文档版权保护方案对比
前端·pdf·github
kyriewen39 分钟前
手写 Promise.all、race、any:不到 30 行代码,解决并发异步的所有姿势
前端·javascript·面试
brucelee1862 小时前
OpenClaw 浏览器控制(Chrome MCP)完整教程
前端·chrome
ct9782 小时前
React 状态管理方案深度对比
开发语言·前端·react
旅僧2 小时前
Π环境部署(运行 且 无理论讲解)
学习
jushi89992 小时前
Lucas Chess R国际象棋、中国象棋、日本将棋、五子棋训练学习工具游戏软件
学习
胡志辉的博客2 小时前
深入浅出理解浏览器事件循环:从一道输出题讲到 Chrome 源码
前端·javascript·chrome·chromium·event loop
代码不加糖2 小时前
js中不会冒泡的事件有哪些?
前端·javascript·vue.js
自传.2 小时前
尚硅谷 Vibe Coding|第一章 AI 编程基础理论 学习笔记
笔记·学习·尚硅谷·vibe coding