简体   繁体   English

使用 useCallback 有意义吗?

[英]Does it make sense to use useCallback?

I have simple functional component which I'm trying to optimize.我有我正在尝试优化的简单功能组件。 I have a table with buttons in one column, button is separate component.我有一列有按钮的表格,按钮是单独的组件。 I need to pass callback function to this component and I'm trying to do it with useCallback hook.我需要将回调函数传递给这个组件,我正在尝试使用 useCallback 钩子来完成它。 But I need to update some dependencies values in this callback.但是我需要在此回调中更新一些依赖项值。 If I leave them in dependencies useCallback will leave sense, because callback function will be created everytime.如果我将它们留在依赖项中,useCallback 会有意义,因为每次都会创建回调函数。 If I remove them(hiddenField, amountField) from dependencies I will get old previous values for them everytime when selectItem is called and if condition evalustes to "false"(I really don't understand why).如果我从依赖项中删除它们(hiddenField,amountField),我将在每次调用 selectItem 并且条件评估为“false”时为它们获取旧的先前值(我真的不明白为什么)。 Does it make sense to use useCallback in my case?在我的情况下使用 useCallback 有意义吗?

export function TestComponent({ field, hiddenField, amountField, changeField }) {
    const selectItem = useCallback(() => {
    const fieldId = field.attributes.Id;
    if (hiddenField.get('id') !== fieldId) {
        changeField(hiddenField, fieldId);
    }
    changeField(amountField, field.attributes.amount);
  }, [field.attributes.amount, field.attributes.fieldId]);// eslint-disable-line react-hooks/exhaustive-deps
return (<ButtonComponent field={field} click={selectItem} />);
}

I veryfied that the cause of using old values in callback function is clousure.我很清楚在回调函数中使用旧值的原因是 closure。 And for getting new values I need to add hiddenField, amountField as useCallback's dependencies.为了获得新值,我需要添加 hiddenField、amountField 作为 useCallback 的依赖项。 But if I do that - wrapping callback in useCallback will be useless, because selectItem function will be created on each render anyway但是如果我这样做 - 在 useCallback 中包装回调将是无用的,因为无论如何都会在每次渲染时创建 selectItem 函数

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM