useRef

Gabriel Castro
3 min readMar 17, 2021

Lets say your building out a profile component, in this file you have a form for your user to fill out. This form you have multiple fields such as name, e-mail, address etc. Each of these fields are required to be filled for your application to render correctly, however for the user this can become very overwhelming. Enter the useRef hook, we can use this hook to allow us to nudge our user along, and get them started.

Getting Started

Alright, so we know that with useEffect hook it acts as a lifecycle method(feel free to check out a previous blog post here where I cover this in depth). We can use this to help us in conjunction with our useRef hook to set up a focus input, so that when the user first loads the page their cursor auto-focuses on the first input field on our profile component.

First, lets start by creating our new react app in our terminal by running…

npx create-react-app my-profile-app

Secondly we can go ahead and cd into the app…

my-profile-app

Finally we can open it up in our trusty IDE, for me this will be Visual Studio Code. When opened we should have our boilerplate React App that looks something like this…

Just for simplicity I am going to clean up this file structure a bit, you don’t need to do this, but just for my own personal sanity. I will be removing everything in App.js except the function, and I will also remove most of the files and their imports. Should end up with something like this…

now if we run…

npm start

it should just be a blank white page.

OK! lets go ahead and build this thing! first thing were going to need is a new component for our profile. can do this by creating a new file in our src folder and naming it Profile.js

Once created, we can then go ahead create an arrow function that will return our Profile and export it to our App.js file to render it on the page…

Now we have out new component created, we can go ahead and use our usRef hook by setting a inputRef to null to start

const inputRef = useRef(null)

With this we can now use our useEffect hook to have our inptRef set our current focus …..

useEffect(() => {
inputRef.current.focus()
},[])

Finally we can use our inputRef to focus on the input text box..

return (
<div>
<input ref={inputRef} type='text' />
</div>
)
}

Now our component should look something like this ..

import React, { useEffect, useRef } from 'react'const Profile = () => {const inputRef = useRef(null)useEffect(() => {
inputRef.current.focus()
},[])
return (
<div>
<h5> username </h5>
<input ref={inputRef} type='text' placeholder='username' />

</div>
)
}
export default Profile

and if we run our npm start in our terminal once the page loads it should auto focus on our text box.

From here we can easily build out our Profile form with the additional information we want to collect.

Happy Coding!

--

--

Gabriel Castro

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