useRef
Topic 6 in React Hooks: Tyler McGinnis
The useState
hook gives you two things, the ability to persist state across renders (function calls to the component), and the ability to trigger an update to that state and re-render.
Without persistence, you can’t have dynamic data, without the trigger, you couldn’t update the UI.
What about if you’re not dealing with the UI bit and don’t need to trigger the update? You just need the persistence part.
For example, let’s say you have an interval that you want to stop. You create the interval in useEffect, to clear it you need the id. You want that outside the useEffect scope, so you declare a variable in the function component to store it.
But that will be wiped every time the component renders, all the values will be unique to the function invocation.
This is where useRef
comes in. The use case is when you want to persist a value across renders without triggering a re-render when it’s updated. You can think of it as returning the first element in the useState
array - the value, without the second.
Use it like let id = useRef(null)
passing an initial value.
The returned object will have a current
property with the current value - update that to set a new persistent value. This won’t trigger a re-render of the component.
The most common use case for useRef
is to get access to DOM nodes. You can use it something like this:
function Form() {
const nameRef = React.useRef();
const emailRef = React.useRef();
const passwordRef = React.useRef();
const handleSubmit = e => {
e.preventDefault();
const name = nameRef.current.value;
const email = nameRef.current.value;
const password = passwordRef.current.value;
//do something
}
return (
<React.Fragment>
<label>
Name:
<input placeholder="name" type="text" ref={nameRef} />
</label>
<label>
Email:
<input placeholder="email" type="text" ref={emailRef} />
</label>
<label>
Password:
<input placeholder="password" type="text" ref={passwordRef} />
</label>
</React.Fragment>
)}
Whenever you pass the value you get back from useRef
to a ‘ref’ prop in a React element React will assign the DOM node to the current prop of the reference allowing you to access its properties and methods (like its current value here).
You could also do something like <button onclick={() => nameRef.current.focus()}>
to focus on the dom element.