1

Is it safe to use such a pattern:

const appLoaders = useMemo(() => React.createRef(), [])

The thing is I use this ref in useEffect and it is needed in the dependency array (exhaustive-deps). The above pattern does the trick and everything seems to work - without the memo, when I put the ref in the dependency array the app was in constant rerender.

I am just wondering if there are some 'traps' that will surprise me in certain circumstances.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Maciej Wira
  • 149
  • 1
  • 10
  • I have used the createRef in memo when I need an array of refs, and it works fine. Check your useEffect instead, usually the useEffect is the one cause forever loop, keep in mind that it can not check deep object, so I believe it will trick the ref object always as new object, which cause re-render. – Sang Dang Feb 19 '20 at 08:27

1 Answers1

6

Don't see any issue with your version, but

const appLoaders = useRef();

looks much shorter and does exactly the same(referential equality across re-renders, we set initial value, changing value does not cause re-render).

PS Actually useRef is not a replacement for React.createRef(they have different purpose but similar names, sometimes people misunderstand/misuse), so don't be confused by similarity.

But in this particular case they are definitely interchangeable

skyboyer
  • 22,209
  • 7
  • 57
  • 64