简体   繁体   English

useCallback 对非记忆组件有意义吗?

[英]Does useCallback make sense for not memoized components?

During reconciliation react compares trees and gets differences.在和解期间,react 比较树并获得差异。 Does it make sense to decrease those differences by using memoization hooks when components are not memoized?当组件没有被记忆时,通过使用记忆挂钩来减少这些差异是否有意义?

Example:例子:

// Does useCallback make sense here?
const onPress = useCallback(() => console.log('Press!'), []);

return (
  <Pressable onPress={onPress}/> // Pressable is neither a memoized FC nor a PureComponent
)

EDIT: Would be nice to receive some numbers, eg performance decrease/improvement in ms, and especially for react native.编辑:很高兴收到一些数字,例如以毫秒为单位的性能下降/改进,特别是对于本机反应。

So react automatically have a memoize system that checks the diffs of all components props when rendering, regardless of your component being memorized.因此,React 自动拥有一个 memoize 系统,该系统在渲染时检查所有组件 props 的差异,无论您的组件是否被记忆。 With this system react checks on only the primitive types (Number, String, Boolean, etc).使用此系统,仅对原始类型(数字、字符串、布尔值等)做出反应检查。

But if you pass a function as props and want react to memoize that function calls then the useCallback becomes useful.但是如果你将一个函数作为 props 传递并且想要对函数调用做出反应,那么 useCallback 就变得很有用了。

react useCallback useCallback 反应 useCallback useCallback

No. React is way too fast in general.不。一般来说,React 太快了。 useCallback and useMemo are supposed to be used only when required. useCallbackuseMemo应该在需要时使用。

Note: " Premature optimization is the root of all evil " ref注意:“过早的优化是万恶之源参考

useCallback and useMemo come with their own overheads. useCallbackuseMemo有自己的开销。 Check this , Kent C Dodds goes in more depth about this.检查这个,Kent C Dodds 对此进行了更深入的研究。

Think about it this way:这样想:

When you scroll a webpage, numerous re-renders keep happening.当您滚动网页时,会不断发生大量重新渲染。 Even during certain animations there are lot of re-renders but we don't face performance issues due to the speed of browser.即使在某些动画期间,也会有很多重新渲染,但由于浏览器的速度,我们不会遇到性能问题。

Just to cover extreme cases I'd also suggest you a read of layout thrashing and debounce input handlers只是为了涵盖极端情况,我还建议您阅读布局抖动去抖动输入处理程序

I don't think so.我不这么认为。 This is the example in the React.org site.这是 React.org 站点中的示例。

const memoizedCallback = useCallback(
  () => {
    doSomething(a, b);
  },
  [a, b],
);

Here [a, b] is a dependency list.这里 [a, b] 是一个依赖列表。 This means callback is called automatically when a or b has changed.这意味着当 a 或 b 发生变化时会自动调用回调。 It seems to be not called like yours.它似乎不像你的那样被称为。 You passed no dependencies and callback will not be called.您没有传递任何依赖项,并且不会调用回调。 I think you can change in this way if you wanna use callback.如果您想使用回调,我认为您可以通过这种方式进行更改。

const [pressed, setPressed] = useState(false)
useCallback(() => console.log('Press'), [pressed])

return (
    <Pressable onPress={() => setPressed (pressed => !pressed) } />
)

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

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