Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

React useRef Hook



The useRef hook in React provides a way to persist values across renders without causing re-renders when the value changes. It returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

Basic Usage

Here's a basic example of how to use useRef:



        import React, { useRef } from 'react';

      function TextInputWithFocusButton() {
        const inputRef = useRef(null);
      
        const handleClick = () => {
          // Focus the input element on button click
          inputRef.current.focus();
        };
      
        return (
          <div>
            <input ref={inputRef} type="text" />
            <button onClick={handleClick}>Focus Input</button>
          </div>
        );
      }
      
      export default TextInputWithFocusButton;
        
      

In this example:

Other Use Cases

  1. Accessing Imperative DOM APIs: You can use useRef to directly access the DOM nodes or other imperative APIs provided by third-party libraries.
  2. Storing Mutable Values: You can store mutable values inside a ref, and they persist across renders without causing re-renders.
  3. Preserving Values between Renders: Since the ref object persists between renders, you can use it to preserve values that you don't want to trigger re-renders.

Best Practices

  1. Avoid Directly Mutating current: While you can directly mutate the .current property of a ref, it's generally not recommended in React code. Instead, use the provided useRef methods (createRef or useRef) to interact with refs.
  2. Uncontrolled Components: useRef is commonly used to access uncontrolled components, such as input fields, without needing to make them controlled components.

When to Use





Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

Zava

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

Zava