ReactJS

ReactJS | useRef Hook with Example

Hello ReactJS friends,

I have already explained about useEffect, useState, and useContext Hook in ReactJS. Today we will learn about useRef Hook in detail.

React UseRef Hook

useRef hook can be used to directly access the DOM element. It allows you to persist values between renders. It can be used to store a mutable value across renders and does not cause a re-render when updated.

When trying to count how many times our application renders using the useState Hook, we would be caught in an infinite loop since this Hook itself causes a re-render. Here comes the use of the useRef hook in ReactJS.

Syntax of useRef Hook in ReactJS:

const refContainer = useRef(initialValue);

Example of useRef Hook in ReactJS:

import React, { Component, createRef } from "react";

Const CustomTextInput = () => {
      textInput = createRef();
      focusTextInput = () => this.textInput.current.focus();
      return (
             <>
                 <input type="text" ref={this.textInput} />
                 <button onClick={this.focusTextInput}>Focus
                 the text input</button>
             </>
      );
}

Conclusion:

This way, you can use useRef Hook in ReactJS. If you have any queries, share them with me through the comments and I will promptly reply to you. Share the tutorial with your friends and stay in touch with us to learn more about ReactJS.

Click to rate this post!
[Total: 3 Average: 4.3]
Bharat Desai

Bharat Desai is a Co-Founder at MageComp. He is an Adobe Magento Certified Frontend Developer 🏅 with having 8+ Years of experience and has developed 150+ Magento 2 Products with MageComp. He has an unquenchable thirst to learn new things. On off days you can find him playing the game of Chess ♟️ or Cricket 🏏.

Recent Posts

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

1 day ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

1 day ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

2 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

3 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

5 days ago

How Upcoming Cookie Changes Will Affect Your E-commerce Website?

The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…

5 days ago