Logo

dev-resources.site

for different kinds of informations.

Hooks Behind The Scenes 3, UseRef!!!

Published at
12/10/2024
Categories
react
useref
hooks
frontend
Author
joedev090
Categories
4 categories in total
react
open
useref
open
hooks
open
frontend
open
Author
9 person written this
joedev090
open
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.
hooks Article's
30 articles in total
Favicon
Hooks Behind The Scenes 3, UseRef!!!
Favicon
A Complete Guide to All React Hooks for Beginners
Favicon
Using useReducer for Complex State Logic
Favicon
Descobrindo o useCallback do React
Favicon
Discovering React’s useCallback
Favicon
Mastering Code Quality in Laravel: Pint with Git Hooks and Docker
Favicon
React: leveraging custom hooks to extract reusable logic
Favicon
Hooks Behind The Scenes 2, useState!!
Favicon
Mastering React Functional Components: Hooks, useEffect, and Lifecycle Explained
Favicon
JSHooks API compare to CHooks
Favicon
The Ultimate Guide to Wall Hanging Hooks and Display Systems for Your Home and Office
Favicon
How to Detect if an Element is in View with React
Favicon
React useQuery : A Complete Guide
Favicon
{useState} HooK { Briefly Explained};
Favicon
React HooK= { Briefly Explained};
Favicon
What is useState?
Favicon
Actions - React 19
Favicon
React controlled and uncontrolled hooks
Favicon
React Concepts: Hook Proximity
Favicon
Demystifying React's useState Hook: A Comprehensive Guide
Favicon
Mastering React Hooks: Best Practices for Efficient and Maintainable Code
Favicon
Designing React Hooks for Flexibility
Favicon
Unleashing the Power of React Custom Hooks
Favicon
Understanding Context Hooks in React: A Beginner's Guide
Favicon
3 Ways To Create Engaging React Loading Screens with Hooks
Favicon
Understanding the useInteractionTimer Hook: Measuring Component Interaction Time in React
Favicon
Cats Fatc's Quick project
Favicon
All About Custom Hooks: Supercharge Your React Components
Favicon
Suggestion for new syntax of React reducers + context
Favicon
How To Define Typescript onChange Event In React

Featured ones: