is passing a ref to useMemo considered cheating?
See original GitHub issueI have an object which is created via useMemo
I do not want this object to be recreated every time a certain dependency changes, and yet I want it to always see the latest version of that dependency (not just what it was upon initial creation)
Currently, I’m doing something like this:
//bar changes between renders
const latestFoo = useRef(bar);
//obj will only be created once, yet it sees the updated latestFoo
const obj = useMemo(() => ({
doSomething: () => {
//use and/or set latestFoo.current
}
}), [latestFoo]);
This feels like a little bit of a lie… because it kindof depends on an updated latestFoo.current
… not really latestFoo
the ref, if that makes sense.
Yet it works fine as far as I can see…
Not sure if I should feel bad about lying to useMemo
about its deps, or if it’s not really a lie at all and this is actually a totally expected use case of useRef
Any tips are appreciated.
P.S. this was prompted by refactoring my code after reading this page, which was an enourmous help in understanding hooks and writing code that uses them more consciously: https://overreacted.io/a-complete-guide-to-useeffect/
@gaearon would you rather me post questions like this somewhere else? Didn’t see a comment section on the site and I don’t use twitter…
Issue Analytics
- State:
- Created 5 years ago
- Comments:7 (2 by maintainers)
Yes, absolutely. Putting
ref
in deps list makes sense (but generally you can consider it to always be the same object anyway). Puttingref.current
in deps list almost never makes sense (because it’s mutated outside of React data flow). If you’re not sure, the lint rule will help you: https://github.com/facebook/react/issues/14920.In general,
ref.current
shouldn’t be in the deps list because its whole purpose is to be mutable outside the React data flow.I think your use case seems fine but maybe adding more details about why you’re doing it (as in, what is foo and bar here) might help discover better ways.