Using useRef and useEffect to store to variables once on mount with functional component

Viewed 334

I have multiple instances of the same component on a page, and I want to give an unique ID to each. Usually in a class component I would declare a this. instance variable, in componentDidMount() set the variable using cuid(), and in the render method reference it.

Now, attempting this in a React functional component and trying to reference it using id.current in the return does not seem to be giving me the expected result. Some components still have a null id. Am I missing anything?

  const id = useRef(null);
  useEffect(() => {
    id.current = cuid();
  }, []);
1 Answers

You can simply pass cuid() as argument to useRef.

const id = useRef(cuid());

This will store a unique id in id variable, which will be created only once on mount.

useEffect with an empty dependency is like a componentDidMount that will run after the render. Hence, setting id there would result in not being available during initial render.

Related