Preact: 10.0.0-alpha.1 - Component returned from useMemo renders when nothing has changed

Created on 12 Mar 2019  路  5Comments  路  Source: preactjs/preact

I was searching for an alternative to shouldComponentUpdate when I discovered that useMemo always executes it callback (tested with an empty array and a hard value in array).

In this codesandbox you can see the difference between React and Preact where one renders a single time and the other multiple times (output in console).

All 5 comments

After some testing there doesn't appear to be anything wrong with useMemo itself. 馃檶

The first time it provides the result of the callback and as the value doesn't change the next time it provides the same result, which is correct.

https://github.com/developit/preact/blob/8042857c05f65d3078e4786d9030be4951c69104/hooks/src/index.js#L145-L156

Not sure what causes the difference in rendering between React and Preact.. Just a wild assumption here, but shouldn't a component be prevented from rendering again when nothing (props / state) has changed?

Hmm - this seems like it might be mixing up useMemo and React.memo. The former is a hook that only invokes its argument when values change, whereas the latter is a replacement for shouldComponentUpdate:false:

https://github.com/developit/preact/blob/ddab4781de763465a641a7022d3f686ba88197dc/compat/src/index.js#L281

import { memo } from 'preact/compat';
const Foo = ({ a, b }) => <div>{a}{b}</div>;
const MemoizedFoo = memo(Foo);

Could be related to #1322 - using useMemo to return the same VNode is similar to what #1322 is doing I think

FYI: We've shipped the strictly equal vnode optimization earlier this year. I'm unable to reproduce the issue in the linked codesandbox when updating to the latest version of Preact :tada:

Great to hear, thanks Marvin! 馃檶

Was this page helpful?
0 / 5 - 0 ratings