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

Difference with use-memo-one? #3

Open
tkrotoff opened this issue Jun 20, 2019 · 6 comments
Open

Difference with use-memo-one? #3

tkrotoff opened this issue Jun 20, 2019 · 6 comments

Comments

@tkrotoff
Copy link

There is already a "popular" project that aims to solve the same problem: https://github.com/alexreardon/use-memo-one

What's the difference?
Here the implementation: https://github.com/alexreardon/use-memo-one/blob/v1.1.0/src/index.js

@Andarist
Copy link
Owner

They dont quite solve the same problem. useConstant(fn) is like useMemoOne(fn, []). This means that useConstant doesnt allow for cache invalidation, it just creates something and use created thing through the whole lifetime of the component - it’s implementation is much shorter than useMemoOne and for simplicity i prefer this one, especially because i dont have any use cases which useMemoOne would solve for me at the moment. useMemo and useConstant are everything I need. Also - mine library was released before the other one. Not that it matter anyhow (they solve similar, but imho different problem), but saying that there is already other similar project might be a little bit confusing ;)

@hasufell
Copy link

hasufell commented Jul 9, 2019

Is that really the shortest implementation? I'm not sure why this wasn't used:

export function useConst<T>(value: T | (() => T)): T {
  const [state] = useState<T>(value);
  return state;
}

It also runs only once.

@Andarist
Copy link
Owner

Andarist commented Jul 9, 2019

See - #4 (comment)

@isBatak
Copy link

isBatak commented Apr 21, 2021

I have a feeling it will not work in Concurrent Mode.
Imagine this scenario:

  1. component starts rendering
  2. ref is updated with some value
  3. react decide to throw away the whole chunk of work and doesn't commit
  4. you end up with the wrong value in the ref, at least not the latest value

@Andarist
Copy link
Owner

If React decides to throw away the whole chunk of work then it should also throw away whatever got stored in a ref and then with the next render the value should be reinitialized - at least this is my current understanding and this is how it behaved within the <StrictMode/>.

@JounQin
Copy link

JounQin commented Sep 12, 2021

I think it is just like useMemo(fn, [])? use-memo-one use a persistent cache, which is not related here.

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