DEV Community

m0nm
m0nm

Posted on

3 1

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 ?

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay