DEV Community

joedev090
joedev090

Posted on

Hooks Behind The Scenes 3, UseRef!!!

In this post let's talk about!!!!

UseRef

  • UseRef allow us to access DOM elements.
  • Create mutable variables which will not re-render the component.

No worries!!!

This is not only theory....

Let's make our first practice.

  • The first use case of UseRef is to create a mutable variable without causing re render.

Count the renders of a input with useRef

Image description

And the code for this:

import {useState, useEffect, useRef} from "react";

export default function App() {
    const [name, setName] = useState("");
    const count = useRef(0);


    useEffect(() => {
        count.current = count.current + 1;
    })


    return (
        <>
            <input type="text" onChange={ (e) => setName(e.target.value) } />
            <h2>Name: {name}</h2>
            <h2>Renders: {count.current}</h2>
        </>
  )
}

Enter fullscreen mode Exit fullscreen mode

We are using useRef to add the count var and when the input changes, we are increasing in one the count.

  • The second use case, Accessing the DOM elements.

The easiest way to change the dom in React is with useRef.

Let's check the next code:

import {useRef} from "react";

export default function App() {
    const inputElementRef = useRef(null);

    const handleClick = () => {
        inputElementRef.current.value = "Hello World";
    }


    return (
        <>
            <input type="text" ref={inputElementRef} />
            <button onClick={handleClick}>Change DOM input!</button>
        </>
  )
}

Enter fullscreen mode Exit fullscreen mode

It will show this:

Image description

As we can see, the inputElementRef is declared with useRef(null) and then we can change the value after clicked only with this line:

inputElementRef.current.value = "Hello World";

A piece of cake!!

Finally in the same way, if you want to change the style of the input for example:

The width and focus:

Image description

We do that with this code:


    const handleClick = () => {
        inputElementRef.current.value = "Hello World";
        inputElementRef.current.style.width = '500px';
        inputElementRef.current.focus();
    }


Enter fullscreen mode Exit fullscreen mode

Conclusion:

const myVar = useRef(initialValue);

myVar.current to update myVar.

  • useRef is a hook to allow us to create mutable variables which don't cause re-render.
  • Very useful to direct access DOM elements.

Top comments (0)