reactjs(useRef Hook)

The useRef hook notes:

useRef(initialValue)

// In the above line the initialvalue passed is assigned to the ref object's current property.

Returns:

useRef hook returns an object with a single property.

Lets understand its working with the help of sample code illustrated below:

In this example code, clicking the button will focus the input:

import { useRef } from 'react'; // In this line we are importing the useRef hook so that it becomes available to use in below functional component.

export default function Form() {

const inputRef = useRef(null); // In this line we are initializing null to the ref object's current property and further we can set it to something else, we can directly mutate the inputRef.current value also unlike setState hook it would not trigger re-rendering of component due to valuchange happening, thus its perfect for storing information that does not have any impact in its visual output.

function handleClick() {

inputRef.current.focus(); // In this line we have inputRef.current holding input element refrence because we passed it to ref attribute of input element in below code, that is the why we are now able to access the input element properties(for example focus in this case)

}

return (

<>

<input ref={inputRef} /> // In this line we are passing ref object as a ref attribute to the JSX DOM node, by doing this we get this node reference and then we will be able to access its properties.

<button onClick={handleClick}>Focus the input </button> // In this line the button gets created, and on click of this button, handleClick function is being called.

</>

);

}

// Article ends here...

Thanks, Happy Coding.