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

useRef for creation of objects? #160

Closed
vikr01 opened this issue Apr 25, 2020 · 2 comments
Closed

useRef for creation of objects? #160

vikr01 opened this issue Apr 25, 2020 · 2 comments

Comments

@vikr01
Copy link

vikr01 commented Apr 25, 2020

I've been seeing a common pattern of creating an object that is an instance of a class in a useRef call:

const mapRef = useRef(new Map());

Can we maybe come up with a version of useRef that works a bit similarly to useMemo, but that it only executes the function the first time?:

const mapRef = useCreationRef(()=>new Map());

Looking at this comparatively on jsperf, it seems quite clear that the second version would always be faster when it involves creation of class objects. Especially when considering custom class objects, which could have constructors that do a lot more than just initialization.

If it's welcome, I'm happy to put up a PR for this.

@theKashey
Copy link

why you could not store data in the state?
why you could not transfer data from the state?

 useRef(useState(() => new Map())[0]);

@vikr01
Copy link
Author

vikr01 commented Apr 25, 2020

why you could not store data in the state?
why you could not transfer data from the state?

 useRef(useState(() => new Map())[0]);

I didn't say I did it, so I'm not sure why you're asking me. There's a ton of cases I'm seeing like this at Facebook.

Looks like Dan already gave an answer like this on a similar thread facebook/react#14490 (comment).

@vikr01 vikr01 closed this as completed Apr 25, 2020
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