DEV Community

m0nm
m0nm

Posted on

Storing variables with useRef ?

React useRef is a hook used to reference html elements (commonly inputs).

If we read the useRef definition from React docs:

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

So by reading above we can use useRef to persist variables throughout the lifetime of our app.

function App() {
    const greeting = useRef("hello world")

    //  mutating the object
    ref.current = "goodbye world"
} 
Enter fullscreen mode Exit fullscreen mode

Why not use a plain variable ?

The problem with variables is that they get re-initialized every time when you refresh the page or the component gets re-rendered

What about useState ?

Sure the state is persisted But the difference is when you update the state the component gets re-rendered.

What are the use cases ?

The only time i've found a use case for useRef is when i was building an infinite scroll component,

When the user reaches the end of the page the component fetches more data based on a page token (it represent the current page). The page token need to be updated on every subsequent request to match the next page. This is where i found useRef suitable for the job.

That's why i started this disscussion, What is your opinion on using useRef for storing variables ? Did you use it to solve a problem ?

Latest comments (0)