Skip to content

useCallback() alternative implementation #14253

Closed
@muqg

Description

@muqg

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))
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions