简体   繁体   English

如何记忆自定义 React 钩子

[英]How to memoize custom React hook

const useSomeHook = ({number}) => {
  const [newNumber, setNewNumber] = useState(0)

  useEffect(() => {
    setNewNumber(number + 1)
  }, [number])
}

const SomeComponent = ({number, value, ...restProps}) => {

  useSomeHook({number})


  return <div>{number}</div>
}

Let's imagine I have this case.假设我有这个案例。 Each time when in SomeComponent come some new prop, it will call my useSomeHook hook, but I want to prevent it.每次在SomeComponent中出现一些新道具时,它都会调用我的useSomeHook钩子,但我想阻止它。 I want to call it only when the number is changed ( memoize it).我只想在number更改时调用它( memoize它)。 In other cases, don't touch it.在其他情况下,请勿触摸它。 But I haven't found any solving with this case.但我还没有找到任何解决这个案例的方法。 Could you help me solve this issue?你能帮我解决这个问题吗?

You can not prevent calling hook, this will lead to invariant violation error.你不能阻止调用钩子,这会导致不变量违反错误。 Every hook in component should be executed on each render.组件中的每个钩子都应该在每次渲染时执行。 You should rely on useEffect dependencies argument to run conditional code only if value changes.仅当值更改时,您才应依赖useEffect依赖项参数来运行条件代码。

I think you are looking for useMemo :我认为您正在寻找useMemo

function SomeComponent({number}) {
    const expensiveValue = useMemo(() => {
         return doSomeExpensiveCalcolationWith(number)
    }, [number])
    return <div>{expensiveValue}</div>
}

In this case, expensiveValue will be recalculated only when number changes, otherwise its value will stay the same across multiple renders.在这种情况下,仅当数字更改时才会重新计算expensiveValue的值,否则它的值将在多次渲染中保持不变。

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

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