Search code examples
reactjsreact-hooksuuidreconciliation

What is the purpose of using useRef(uuid())?


Recently I've found pretty strange and new to me way of using useRef. useRef(uuid()) - is it a valid way of generating stable id, or something that is should rather be avoided?


Solution

  • It will generate a stable id, but in it's current form it will call uuid() each and every render cycle. Here it's likely not a big deal, but imagine instead if it was a heavy function. Calling it each render cycle could effect performance. Instead you might consider using a useEffect hook to assign the ref value.

    Example:

    const idRef = useRef();
    
    useEffect(() => {
      idRef.current = uuid();
    }, []);
    

    You could also create a getter function that returns the current ref value and only creates it when necessary.

    Example:

    const idRef = useRef();
    
    const getId = () => {
      if (!idRef.current) {
        idRef.current = uuid();
      }
      return idRef.current;
    };
    

    See How to Create Expensive Objects Lazily