Skip to content

[Hooks] Alternative useCallback implementation #83

Closed
@edkalina

Description

@edkalina

According to this page useCallback(fn, inputs) is equivalent to useMemo(() => fn, inputs)

I suggest another one (implemented with current hooks):

function useHandler(handler) {
  const holder = useRef();
  holder.current = handler;

  // TODO: avoid useMemo?
  return useMemo(
    () =>
      function(...args) {
        return holder.current.apply(this, args);
      },
    []
  );
}

It has advantages:

  • no need to specify inputs, latest instance of handler will be called
  • result of useHandler is constant for all rerenders

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