Search code examples
reactjsreact-hooksrefmemo

React.createRef() inside useMemo


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.


Solution

  • 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