Andrik Dizhak
Andrik Dizhak

Reputation: 135

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?

Upvotes: 2

Views: 665

Answers (1)

Drew Reese
Drew Reese

Reputation: 203348

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

Upvotes: 3

Related Questions