useRef Part II

Gabriel Castro
2 min readMar 24, 2021

--

Last week I started a blog post about how to useRef in order to focus your cursor on a particular textbox when our users first open our website. I thought we take a look at another use case for using useRef.

Deeper Dive

I thought we would back track a little to take a deeper look at useState vs. useRef Keeping it simple lets create a counter that counts by one each time we want our state to update. You may think of doing something like this…

import React, { useState, useEffect } from 'react'export default function App() {
const [twitterHandle, setTwitterHandle] = useState('')
const [renderCount, setRenderCount]= useState(0)
useEffect(() => {
setRenderCount(prevRenderCount => prevRenderCount + 1)
})
return (
<div>
<input value={twitterHandle} onChange={e => setTwitterHandle(e.target.value)} />
<div> my twitter handle is @{twitterHandle}</div>
<div> Ive rendered {renderCount} characters </div>
</div>
)
}

Here we are setting a twitterHandle with our useState hook while also setting our counter. Our useEffect is updating by one each time our page is rendered. The issue with this is we have now created an infinite loop. If we run this code our renderCount will continuously update instead of when we actually have typed a character into our input.

Infinite loop

Fix?

Now that we understand why we would want to avoid useState in this instance, lets look at a way we can useRef to get the desired result.

import React, { useState, useEffect, useRef } from 'react'export default function App() {
const [twitterHandle, setTwitterHandle] = useState ('')
const renderCount = useRef(0)
//object with a current property, once updated gets persisted on each renderuseEffect(() => {
renderCount.current = renderCount.current + 1
})
//updating our current render count + 1 each time character is enteredreturn (
<div>
<input value={twitterHandle} onChange={e => setTwitterHandle(e.target.value)} />
<div> my twitter handle is @{twitterHandle}</div>
<div> Ive rendered {renderCount.current} characters </div>
</div>
)
}

Here our code is very similar, but instead of using useState to handle our count, we are using useRef. This hook is allowing us to get the current count of an instance each time a character is typed in without it continuously re-rendering the count.

Renders only once per input

happy coding!

--

--

Gabriel Castro
Gabriel Castro

Written by Gabriel Castro

Full Stack, Software Engineer. Focus in Rails, JavaScript and React.

No responses yet