Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useCallback() alternative implementation #14253

Closed
muqg opened this issue Nov 16, 2018 · 2 comments
Closed

useCallback() alternative implementation #14253

muqg opened this issue Nov 16, 2018 · 2 comments

Comments

@muqg
Copy link

muqg commented Nov 16, 2018

useCallback provides a way to memoize callbacks based on whether an array of given values changes. I have been wondering if it could work like something similar to this instead:

function useStatic(cb) {
  const callback = useRef(cb)
  callback.current = cb

  const mem = useRef((...args) => callback.current(...args))
  return mem.current
}

Note that this is just a mock implementation to illustrate my idea. This hook above will always return the same function instance that is kept within the reference object, while always calling the latest version of the callback argument. This way the need to pass props to be compared is omitted which could also be an improvement to its performance.

Here is a side to side usage comparison:

function MyComponent({title}) {
  // Will return the memoized callback if title didn't change.
  const current = useCallback(() => alert(title), [title])

  // Will return a memoized callback, even if title changes,
  // while there is also no need to check if it did change.
  const alternative = useStatic(() => alert(title))
}
@gaearon
Copy link
Collaborator

gaearon commented Nov 16, 2018

Please see reactjs/rfcs#83 (comment) and #14099. Thanks!

@gaearon gaearon closed this as completed Nov 16, 2018
@gaearon
Copy link
Collaborator

gaearon commented May 4, 2022

We've submitted a proposal to solve this. Would appreciate your input!

reactjs/rfcs#220

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants