React: Pass dependencies to `useMemo` callback as arguments

Created on 12 Feb 2019  路  3Comments  路  Source: facebook/react

Do you want to request a feature or report a bug?

Feature

What is the current behavior?

The useMemo factory function does not receive any arguments.

What is the desired behavior?

The useMemo factory function would receive the dependencies as arguments.

Why?

This would allow more compact syntax for memoizing components because of implicit returns and desctructuring. This came to mind after experiencing some of the issues in #14110. There may be other potential use cases too

Example of current behavior

const Avatar = () => {
  const [src] = useSomeGlobalState([
    state => state.user.avatar.src
  ]);
  return useMemo(() => <img src={src} />, [src])
}

Example of proposed behavior

const Avatar = () => 
  useMemo(
    (src) => <img src={src} />,
    useSomeGlobalState([state => state.user.avatar.src])
  );

Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?

React 16.8.1

Feature Request

Most helpful comment

@threepointone Thanks for the feedback 馃憤

All 3 comments

I'd argue that the former is explicit, while the latter isn't. Leaving aside that this pattern isn't recommended (we recommend hooks at the 'top' level only, much like imports), the proposal would only be useful when using an array that another function returns, whereas in practice that's a very small fraction of useMemo usages; in practice, you'd be using dependencies from different sources. It would also be confusing when people do use closures (which we recommend for all hooks) but not see updates.

I'm going to close this because I don't think we'll be doing this any time soon.

@threepointone Thanks for the feedback 馃憤

@threepointone this seems like a good topic for the Hooks FAQ 馃檪

Was this page helpful?
0 / 5 - 0 ratings