React 常用 Hooks 和使用的易错点

常用 Hooks
  1. useState:声明状态变量。

    复制代码
    typescript
    复制代码
    const [count, setCount] = useState<number>(0);
  2. useEffect:副作用处理。

    复制代码
    typescript复制代码useEffect(() => {
        // 执行副作用
        return () => {
            // 清理副作用
        };
    }, [dependency]);
  3. useContext:使用上下文。

    复制代码
    typescript
    复制代码
    const value = useContext<MyContextType>(MyContext);
  4. useReducer:复杂状态逻辑管理。

    复制代码
    typescript
    复制代码
    const [state, dispatch] = useReducer(reducer, initialState);
  5. useMemo:性能优化,记住计算结果。

    复制代码
    typescript
    复制代码
    const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
  6. useCallback:性能优化,记住函数定义。

    复制代码
    typescript复制代码const memoizedCallback = useCallback(() => {
        doSomething(a, b);
    }, [a, b]);
Hooks 使用的易错点
  1. useStateuseEffect 依赖

    • 易错点 :在useEffect中忘记依赖数组,导致无限循环。

    • 解决方案 :确保在useEffect中添加依赖数组。

    复制代码
    typescript复制代码useEffect(() => {
        // 依赖a和b
    }, [a, b]);
  2. useEffect 清理函数

    • 易错点 :在useEffect中没有正确地清理副作用,导致内存泄漏。

    • 解决方案 :确保在useEffect中返回一个清理函数。

    复制代码
    typescript复制代码useEffect(() => {
        const subscription = subscribeToSomething();
    ​
        return () => {
            subscription.unsubscribe();
        };
    }, []);
  3. useMemouseCallback 依赖

    • 易错点 :在useMemouseCallback中忘记依赖数组,导致没有性能优化效果。

    • 解决方案 :确保在useMemouseCallback中添加依赖数组。

    复制代码
    typescript复制代码const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
    const memoizedCallback = useCallback(() => {
        doSomething(a, b);
    }, [a, b]);
  4. useReducer 初始状态

    • 易错点 :在useReducer中直接修改状态对象。

    • 解决方案 :确保在reducer函数中返回新的状态对象。

    复制代码
    typescript复制代码const reducer = (state: StateType, action: ActionType): StateType => {
        switch (action.type) {
            case 'UPDATE':
                return { ...state, value: action.payload };
            default:
                return state;
        }
    };
相关推荐
字节架构前端26 分钟前
k8s场景下的指标监控体系构建——Prometheus 简介
前端·架构
奕羽晨39 分钟前
关于CSS的一些读书笔记
前端·css
Poetry2371 小时前
大屏数据可视化适配方案
前端
遂心_1 小时前
用React Hooks + Stylus打造文艺范的Todo应用
前端·javascript·react.js
轻语呢喃1 小时前
<a href=‘ ./XXX ’>,<a href="#XXX">,<Link to="/XXX">本质与区别
前端·react.js·html
用户3802258598241 小时前
vue3源码解析:watch的实现
前端·vue.js·源码
F2E_Zhangmo1 小时前
第一章 uniapp实现兼容多端的树状族谱关系图,创建可缩放移动区域
前端·javascript·uni-app
鹏程十八少1 小时前
3. Android 第三方框架 Okhttp, Retrofit 的动态代理和适配器模式深度解读三
前端
阿怼丶1 小时前
🚶‍♂️基于 Three.js 的自定义角色漫游系统实战:支持碰撞检测与动画控制
前端·three.js