Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 26, 2022 12:54 pm GMT

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"} 

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 ?


Original Link: https://dev.to/m0nm/storing-variables-with-useref--5e4o

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To