React: memo vs. useMemo

Created on 17 Jan 2019  ·  5Comments  ·  Source: facebook/react

I'm a little confused about the relationship between memo() (the core API function) and useMemo() (the hook).

Specifically, can memo() be implemented in terms of useMemo() ?

I tried this but it doesn't work, it just keeps re-rendering:

const my_memo = Component => props => {
  return React.useMemo(() => <Component {...props} />, [props]);
}

Most helpful comment

I tried this but it doesn't work, it just keeps re-rendering:

props itself is a new object on every render. memo() does shallow comparison by default. You can think of memo() as a useMemo() with a list of all your props like [props.foo, props.bar, props.foobar] except you don't need to type them all manually. It's a shortcut for the most common case.

Can someone please clarify what sort of bugs and how to avoid them? Thanks!

This is about shouldComponentUpdate but the issue is similar: https://github.com/reactjs/reactjs.org/issues/1149. Basically — if your component breaks without memo then you're not using it correctly. It only serves as perf optimization.

All 5 comments

Also, the react docs state:

Do not rely on it to “prevent” a render, as this can lead to bugs.

Can someone please clarify what sort of bugs and how to avoid them? Thanks!

I tried this but it doesn't work, it just keeps re-rendering:

props itself is a new object on every render. memo() does shallow comparison by default. You can think of memo() as a useMemo() with a list of all your props like [props.foo, props.bar, props.foobar] except you don't need to type them all manually. It's a shortcut for the most common case.

Can someone please clarify what sort of bugs and how to avoid them? Thanks!

This is about shouldComponentUpdate but the issue is similar: https://github.com/reactjs/reactjs.org/issues/1149. Basically — if your component breaks without memo then you're not using it correctly. It only serves as perf optimization.

Yup, this seems to work. Thanks!

const memo = Component => props => {
  return React.useMemo(() => <Component {...props} />, Object.keys(props).map(key => props[key]));
}

I have a test case here fwiw: https://codepen.io/dakom/pen/xmNepg

Feel free to close the issue :)

(by "work" I mean for a simple case, not as exhaustive of course)

Yeah — the problem with that is it'll break if order or key changes or if you add or remove keys.

Was this page helpful?
0 / 5 - 0 ratings