3 ms·
To be fair, if you're passing the closure to a component that extends PureComponent or is wrapped by React.memo, then memoizing the closure will ensure you take
by RussianCow 7y ago
To be fair, if you're passing the closure to a component that extends PureComponent or is wrapped by React.memo, then memoizing the closure will ensure you take advantage of that optimization in the child; otherwise, you're passing a branch new function reference on every render, which means the child is needlessly re-rendering. At work, we have many components that are very complex but take a limited set of props, so these kinds of optimizations are absolutely vital for good performance.
That said, you're correct in that this should be the exception and not the rule. It's pointless to do this for a component that returns a single element, as the virtual DOM reconciliation will be much faster than the memoization + props comparison.
- erikpukinskis 7y agoIf you have limited props, why would your component be rendering often?
- RussianCow 7y agoBecause the parent might render often.
- erikpukinskis 7y agoThat shouldn’t cause the child to re-render?
- RussianCow 7y agoI'm not sure why you think it wouldn't. Any time a component renders, React also renders all of its children except the ones for which shouldComponentUpdate returns false. If that is defined by using PureComponent or React.memo on a child, then you have to make sure that the props you pass in are not going to change on every re-render (i.e. you can't pass an un-memoized callback because a new function reference will be created on every render). I've created a CodePen to illustrate: https://codepen.io/RussianCow/pen/xxbERLL https://codepen.io/RussianCow/pen/xxbERLL Open the console and watch as the "render child" message is logged once per second, showing that the child is re-rendered every time the parent is.