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: 4 Average: 4]
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

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

6 days ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

1 week ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

1 week ago

Top 10 Tips to Hire Shopify Developers

As the world of eCommerce continues to thrive, Shopify has become one of the most…

2 weeks ago

Managing Browser Events and Navigation in Shopify Remix: useBeforeUnload, useHref, and useLocation Hooks

Shopify Remix is an innovative framework that provides a streamlined experience for building fast, dynamic,…

2 weeks ago

Ultimate Guide to Hiring a Top Shopify Development Agency

Building a successful eCommerce store requires expertise, and for many businesses, Shopify has become the…

2 weeks ago