What is useref hook in react js

useRef is a React Hook which allows to create a reference to a DOM element or the value that persevere across renders without causing re-renders. It’s normally used for interacting with DOM elements , but using it we can also store any mutable value and that doesn’t need to be trigger.

Working Process of useRef:
It (useRef) returns the mutable object value with the single property, which can be use to store reference to a DOM element or DOM value.
Updating the useRef values does not cause the component to re-render unlike useState

Example :

import React, { useRef } from 'react';

function TextInputWithFocusButton() {
  // Create a ref object and assign it to the input element
  const inputEl = useRef(null);

  const focusInput = () => {
    // Access the input element and call the focus method
    if (inputEl.current) {
      inputEl.current.focus();
    }
  };

  return (
    <div>
      {/* Attach the ref to the input element */}
      <input ref={inputEl} type="text" />

      {/* The input field will be focused, when button is clicked */}
      <button onClick={focusInput}>Focus on the input</button>
    </div>
  );
}
export default TextInputWithFocusButton;

Explanation of the above code process:

Creating the Ref:

const inputref = useRef(null); creates a ref object. Initially, inputref.current will be null.

Attaching the Ref:

attaches the ref to the input element. Now, inputref.current points to the input DOM element.

Using the Ref:

focusInput function is called on the button click, , which uses inputref.current.focus() to focus the input element.

Output

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *