DEV Community

Discussion on: 5 use cases of the useState ReactJS hook

joeattardi profile image
Joe Attardi

You can also use them to store an element ref!
Using a ref is handy but as you probably know, changes to ref.current will not re-render the component.

What if you want it to?

You can use a function ref!

It looks like this:

const [popup, setPopup] = useState();
Enter fullscreen mode Exit fullscreen mode

Then in your JSX:

<div ref={setPopup}></div>
Enter fullscreen mode Exit fullscreen mode

If you aren't familiar with this usage of a ref, a function ref gets called with the element. When the element is removed from the DOM, it is called again and passed null.

You can reference the DOM element now via the popup property (not popup.current as this isn't a "standard" ref.

It can be useful!

colocodes profile image
Damian Demasi Author

Wow, nice trick! Thanks!