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?
Asked
Active
Viewed 282 times
2
-
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 Answers
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;
};

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