简体   繁体   English

我应该添加 useCallback 或 useMemo 到我的效果吗?

[英]Should I add useCallback or useMemo to my effect?

The following tooltip will call the API once the user hovers on a button.一旦用户将鼠标悬停在按钮上,以下工具提示将调用 API。 I wonder if I need to work with useCallback or useMemo to avoid unnecessary API calls?我想知道是否需要使用useCallbackuseMemo以避免不必要的 API 调用? I still struggle to understand when I need one of the two.我仍然很难理解何时需要两者之一。 If it makes sense to add it, how would you do it?如果添加它是有意义的,你会怎么做?

const ProfileTooltip = ({ children, userId }) => {
    const classes = useStyles();
    const [open, setOpen] = useState(false);
    const [profileInfo, setProfileInfo] = useState(false);
  
    useEffect(() => {
      if (!open) {
        return;
      }
  
      const fetchProfileInfo = async () => {
        try {
          const { data } = await api.get(`users/${userId}/info/`);
          setProfileInfo(data);
        } catch (e) {
          setProfileInfo(null);
        }
      };
      fetchProfileInfo();
    }, [open, userId]);
  
    const handleOpen = () => {
      setOpen(true);
    };
  
    const handleClose = () => {
      setOpen(false);
    };
  
    const renderTooltip = () => {
      if (!profileInfo) {
        return;
      }
  
      return (
        <>
          <h3 className={classes.profileName}>
            {profileInfo.firstName} {profileInfo.lastName}
          </h3>
          <p className={classes.headline}>{profileInfo.headline}</p>
          <Button size="small" variant="contained" color="primary" fullWidth>
            Message
          </Button>
        </>
      );
    };
  
    return (
      <div className={classes.root}>
        <Tooltip
          arrow
          classes={{
            tooltip: classes.tooltip,
            arrow: classes.arrow,
            tooltipArrow: classes.tooltipArrow,
            popperArrow: classes.popperArrow,
          }}
          interactive
          placement="top-start"
          onOpen={handleOpen}
          onClose={handleClose}
          title={renderTooltip()}
        >
          {children}
        </Tooltip>
      </div>
    );
  };
  
  export default ProfileTooltip;

useCallback hook is used to memoize callback functions so that they are not re-created every time component re-renders. useCallback钩子用于记忆回调函数,以便在每次组件重新渲染时都不会重新创建它们。 This is useful when you want to pass a function to a child component and that child component depends on reference equality to avoid unnecessary re-renders.当您想要将 function 传递给子组件并且该子组件依赖于引用相等以避免不必要的重新渲染时,这很有用。

useMemo hook is used to memoize values to avoid doing expensive computations on every render of the component. useMemo钩子用于记忆值,以避免在组件的每次渲染上进行昂贵的计算。 Function passed to useMemo runs during rendering, so any code that has side effects should not be written in this function.传递给useMemo的 Function 在渲染期间运行,因此任何具有副作用的代码都不应写入此 function。

I wonder if I need to work with useCallback or useMemo to avoid unnecessary API calls?我想知道是否需要使用 useCallback 或 useMemo 以避免不必要的 API 调用?

Both these hooks won't help in your case.这两个钩子对你的情况都没有帮助。

Side effects such as API calls belong in useEffect hook and to optimize the execution of your side effect, you will need to look at the dependency array of the useEffect hook. API 调用等副作用属于useEffect挂钩,为了优化副作用的执行,您需要查看useEffect挂钩的依赖数组。

You could, however, wrap handleOpen and handleClose functions in useCallback hook.但是,您可以在useCallback挂钩中包装handleOpenhandleClose函数。 Doing this will prevent re-creating these functions on every render and a memoized function reference will be passed to Tooltip component.这样做将防止在每次渲染时重新创建这些函数,并且记忆的 function 引用将传递给Tooltip组件。

You will need to make sure that you get the dependency array of useCallback hook right otherwise you will run into bugs that could be hard to debug.您需要确保正确获取useCallback挂钩的依赖数组,否则您将遇到难以调试的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我的 useMemo useCallback 不会减少渲染次数。 使用 useMemo 和 useCallback 的正确方法是什么? - My useMemo useCallback does not reduce the number of render. What is the correct way to use useMemo and useCallback? useCallback 没有在我的程序中提供我需要的效果 - useCallback not giving the required effect i need in my program useMemo(()=&gt;()=&gt;{}, []) 和 useCallback(()=&gt;{}, []) 一样吗? - Is useMemo(()=>()=>{}, []) the same as useCallback(()=>{}, [])? 如何使用 useMemo 或 useCallback 在 React 中防止不必要的重新渲染? - How do i prevent unnecessary rerendering in React using useMemo or useCallback? 我应该将此 function 包装在 useCallback 中吗? - Should I wrap this function in a useCallback? 为什么在这里使用 useMemo 而不是 useCallback? - Why use useMemo and not useCallback here? useState、UseRef 或 useMemo,我应该更喜欢哪个 - useState, UseRef, or useMemo, what should I prefer 在自定义 hooks 中使用 useCallback 和 useMemo 的要点 - The point of using useCallback and useMemo in custom hooks React class 组件是否有等效于 UseMemo 或 UseCallback 的组件? - Is there an equivalent to UseMemo or UseCallback for React class component? React Docs以及useMemo和useCallback之间的区别 - React Docs and difference between useMemo and useCallback
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM