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

[Hooks] Alternative useCallback implementation #83

Closed
edkalina opened this issue Nov 5, 2018 · 5 comments
Closed

[Hooks] Alternative useCallback implementation #83

edkalina opened this issue Nov 5, 2018 · 5 comments

Comments

@edkalina
Copy link

edkalina commented Nov 5, 2018

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
@gaearon
Copy link
Member

gaearon commented Nov 5, 2018

Yeah, we've considered this. It's not clear however what pitfalls this would have in concurrent mode. The particular implementation you propose would definitely have issues (because it mutates during rendering). The one using an effect (like in our FAQ) would be a bit safer but isn't generic purpose (it requires the tree to commit first) and might also have pitfalls.

We have another idea for how to solve this. I described it briefly in facebook/react#14099 and might add more info there later. Please participate in that issue if you're interested. Thanks!

@ypresto
Copy link

ypresto commented Apr 23, 2020

For someone searching for what is "async safe" or "mutation of ref during rendering" problem, it is described here:
facebook/react#14099 (comment)

In concurrent mode (not yet released), it would "remember" the last rendered version, which isn't great if we render different work-in-progress priorities. So it's not "async safe".

@LiuJi-Jim
Copy link

Looks like ahooks/usePersistFn

@duj26089
Copy link

duj26089 commented Jan 3, 2022

看起来像ahooks/usePersistFn

大佬也研究react么

@gaearon
Copy link
Member

gaearon commented May 4, 2022

We've submitted a proposal to solve this that's largely similar (but works a bit differently). Would appreciate your input.

#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

5 participants