useRef Hook

React‘s useRef hook is a built-in function that allows you to create a mutable ref object in functional components. A ref is a way to store a reference to a DOM element or a value that persists across renders, without triggering a re-render.

To use useRef, you first need to create a ref object using the React.useRef() function. This function returns an object that contains a current property. The current property can be used to store any value or reference.

Here’s an example of how you might use useRef to store a reference to a DOM element:

				
					import React, { useRef } from 'react';

function MyComponent() {
  const inputRef = useRef();

  function handleClick() {
    inputRef.current.focus();
  }

  return (
    <div>
      <input type="text" ref={inputRef} />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  );
}

				
			

In this example, we first import useRef from the React library. We then declare a new ref called inputRef using the useRef function. We also declare a handleClick function that calls the focus method on the inputRef.current property when a button is clicked.

We then render an input element and a button that calls the handleClick function when clicked. We pass the inputRef ref object to the ref attribute of the input element, which allows us to store a reference to the input element in the inputRef.current property.

When the button is clicked, the handleClick function is called, which calls the focus method on the inputRef.current property. This focuses the input element and allows the user to start typing.

useRef is a powerful hook that allows you to create a mutable ref object in functional components. By using it, you can store references to DOM elements or values that persist across renders, without triggering a re-render.

Join To Get Our Newsletter
Spread the love