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.

Sentry blog image

Identify what makes your TTFB high so you can fix it

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

Read more

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay