Article thumbnail

React useRef hook



All use cases for useRef hook that are popular and less popular. Let's check the use cases, implementation, and how it works in React.


When you compare the documentation and code written by developers, you can often find a completely different use for certain things.

Technology is evolving and it's really problematic to handle all use cases - especially when you are writing libs/frameworks.

A typical example of that is useRef() hook which sometimes is used by a community in a different way than described in the docs.

Yup, that's right. That hook has more than one use case.

1. useRef() in documentation

Docs explain useRef() as a hook that allows you to read real DOM data during the component life cycle. For example, if you would like to read the position of HTML div in real DOM, useRef() is the perfect tool.


2. Candidate for caching

We have a big user list that needs to be filtered by the query. This is an ideal candidate for caching. With caching - aka "flyweight" pattern - we can reduce the time complexity of the search algorithm. Of course, it increases memory usage but we're not building Mars lounger so who cares about the small amount of additional memory usage for better UX.

As you probably figured out, in our search function we have a performance bottleneck.


3. Adding caching feature

To cache data in that case useRef() is an ideal candidate.

It's because useRef() is 100% synchronous, which means you can read/write immediately. At this point you are using something similar to class property which can be changed during the object lifecycle.


You have right now the same behavior as class property without a class.

4. Understanding sync vs async

Using useState() setter it can be described as request to change value. React decide when.

Changing value in useRef() it's just immediate change.

The same thing happened in your childhood when your mother asked you to take out the rubbish. It was also not an order but a request, and you did it late or not.


5. Read changes immediately

Look at handleChange() function call. We can read values immediately and they are always up to date. It's because of useRef() usage inside useForm() hook instead of useState().

The setCounter() is used only for trigger rerender - that's all.



I hope you understand useRef() power now.

Looks like someone again created a function with an unfriendly name 👽. As you saw useRef() can be used to access immediate state change, as cache and also, like an option to reading DOM data in real-time.

Feel free to contact me if you have any questions/proposals. Have a nice day and good health!

I create content regularly!

I hope you found my post interesting. If so, maybe you'll take a peek at my LinkedIn, where I publish posts daily.


Add your honest opinion about this article and help us improve the content.

created: 01-06-2022
updated: 16-10-2022