我应该在 useCallback 的依赖项数组中包含 setState 吗? [英] Should I include setState in useCallback's array of dependencies?

查看:38
本文介绍了我应该在 useCallback 的依赖项数组中包含 setState 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    const [active, setActive] = useState(false);

    const onActiveChanged = useCallback(
      isActive => () => {
        // do something
        setActive(isActive);
      },
      [setActive], // or just [] is okay?
    );

当同时使用 useStateuseCallback(或 useMemo)时,我应该在数组中包含 setState依赖?

When using useState and useCallback (or useMemo) together, should I include setState in the array of dependencies?

推荐答案

对此的建议也在 React 文档 - Hooks API 参考.

setState 函数用于更新状态.它接受一个新的状态值并将组件的重新渲染排入队列.

The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component.

setState(newState);

在随后的重新渲染期间,第一个值useState 返回的将始终是之后的最新状态应用更新.

During subsequent re-renders, the first value returned by useState will always be the most recent state after applying updates.

注意

React 保证 setState 函数标识是稳定的,不会重新渲染时发生变化.这就是为什么从 useEffect 中省略是安全的或使用回调依赖列表.

React guarantees that setState function identity is stable and won’t change on re-renders. This is why it’s safe to omit from the useEffect or useCallback dependency list.

这篇关于我应该在 useCallback 的依赖项数组中包含 setState 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆