学习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 }}),每次渲染都会触发子组件更新,应避免直接传递内联对象。
  • 如果重复嵌套使用并且使用的值是相同的则里层的值会覆盖外层的值。
相关推荐
崔庆才丨静觅1 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60612 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了2 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅2 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
执笔论英雄2 小时前
【大模型学习cuda】入们第一个例子-向量和
学习
wdfk_prog3 小时前
[Linux]学习笔记系列 -- [drivers][input]input
linux·笔记·学习
崔庆才丨静觅3 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅3 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment3 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅3 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端