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 doesn't memoize as expected #17221

Closed
cdoublev opened this issue Oct 30, 2019 · 2 comments
Closed

useCallback doesn't memoize as expected #17221

cdoublev opened this issue Oct 30, 2019 · 2 comments

Comments

@cdoublev
Copy link

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

Bug

What is the current behavior?

useCallback doesn't return a memoized function when used as a "higher order ref callback".

https://codesandbox.io/s/snowy-tdd-wb8gu

  1. Click "Toggle" button to unmount the second div node
  2. Open console and look at the output, described by the following quote from the doc

If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one.

https://reactjs.org/docs/refs-and-the-dom.html#caveats-with-callback-refs

What is the expected behavior?

useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed.

https://reactjs.org/docs/hooks-reference.html#usecallback

It doesn't work with useMemo as well, even if #15774 looks similar. It works with a "standard" memoize function, like _.memoize.

As indicated in #17204, I was looking for a way to identify the unmounted node.

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

React 16.11.0

@miturostislav
Copy link

Hi @cdoublev ,
Actually "useCallback" returns a memoized function but when you call that function ("setRefs"), it creates and returns a new function every time.
The inner function is not memoized.
Hope it helps :).

@cdoublev
Copy link
Author

I should stop creating issue at the end of the day. Thank you for enlighting me a little longer @miturostislav. :)

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