2

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?

Andrik Dizhak
  • 95
  • 1
  • 5
  • you use useRef when state management is not required. see another example [here](https://reactjs.org/docs/hooks-faq.html#how-to-create-expensive-objects-lazily) – bogdanoff Oct 13 '22 at 10:01

1 Answers1

3

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

Drew Reese
  • 165,259
  • 14
  • 153
  • 181