Additional Hooks in React - useRef()

Olena Drugalya - Jan 23 '21 - - Dev Community

This blog post continues the series about React Hooks.

It covers one of additional hooks in React - useRef().

What is useRef()?

useRef() is JavaScript function, which creates and returns a mutable JavaScript object.
This hook accepts some value and returns an object with the given value.

Let's look at it more closely below.

How and when use useRef()

To use this hook, you need to import it first from React library like this:

import {useRef} from 'react';
Enter fullscreen mode Exit fullscreen mode

You can use this hook without import as well like this - React.useRef(), for me it's just more convenient to import and destructure first this function and then use it when need in the code.

Afterwards we can set up this hook like this:

const refBox = useRef(initialValue);
Enter fullscreen mode Exit fullscreen mode

In the basic setup above I called a constant refBox not occasionally, but because we can consider it as a box, which contains an object. The object created by useRef()has a mutable value in its .current property. This value is created by initial value passed to the hook.
NOTE: Mutating the .current property doesn’t cause a re-render.

Use cases

  1. Getting access to DOM nodes

The most popular use case for useRef() is getting access to DOM nodes. If you pass the value you get from useRef() as a ref prop on any React element, React will set the .current property of an element to the corresponding DOM node. This allows you to do things like grab input values or set focus, for example in the Form below:

import {useRef} from 'react';

const Form =() =>{

//Here we create ref for input field 
const nameRef = useRef();

//Here variable Name contains the current value of input field 
const name = nameRef.current.value; 

return(
    <>
      <label>
        Name:
        <input
          placeholder="name"
          type="text"
          ref={nameRef}  //here we add ref property to input 
        />
      </label>
      //Here we add an event which gets input focus when user clicks the button
      <button onClick={() => nameRef.current.focus()}>
        Focus Name Input
      </button>
  </>
)
}

Enter fullscreen mode Exit fullscreen mode

2.Storing Values

A unique way to implement a useRef() hook is to use it to store values instead of DOM references. These values can either be a state that does not need to change too often or a state that should not trigger full re-rendering of the component. This can be used when you want to implement toggle function, for example:

let toggled = useRef(false);

  const handleToggle  = () => {
    toggled.current = !toggled.current;
  }

return(
<>
   <label onMouseMove={handleToggle}></label>
</>
)

Enter fullscreen mode Exit fullscreen mode

Conclusion

The useRef() hook is a very handy option for both interacting with DOM elements and storing mutating information in your app without triggering a re-render. However, it is suggested to only use the useRef() when necessary.

Thank you for reading my blog. Feel free to connect on LinkedIn or Twitter :)

Buy Me a Coffee at ko-fi.com

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .