How to use the useRef hook in React



Image not found!!

In React, the useRef hook is used to create a mutable object that persists across renders without causing the component to re-render when the object is changed. This can be useful for accessing and interacting with the DOM directly, managing focus, or persisting values across renders without triggering a re-render.

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

jsx
import React, { useRef, useEffect } from 'react'; function MyComponent() { // Create a ref object const myRef = useRef(null); useEffect(() => { // Access the current property to get the DOM element if (myRef.current) { // Do something with the DOM element myRef.current.focus(); } }, []); return ( <div> {/* Attach the ref to a JSX element */} <input ref={myRef} type="text" /> </div> ); } export default MyComponent;

In this example:

  1. useRef(null) creates a ref object with an initial value of null.
  2. myRef.current provides access to the DOM element. In this case, it's used within the useEffect hook to focus on an input element when the component mounts ([] dependency ensures that the effect runs only once after the initial render).
  3. The ref attribute is used to attach the ref to a JSX element (<input> in this case).

Here are a few common use cases for useRef:

1. Accessing and Modifying DOM Elements

jsx
import React, { useRef, useEffect } from 'react'; function MyComponent() { const myRef = useRef(null); useEffect(() => { if (myRef.current) { // Access or modify the DOM element myRef.current.style.backgroundColor = 'lightblue'; } }, []); return ( <div ref={myRef}> {/* ... */} </div> ); } export default MyComponent;

2. Persisting Values without Causing Re-renders

jsx
import React, { useRef, useState } from 'react'; function MyComponent() { const inputValueRef = useRef(''); const [inputValue, setInputValue] = useState(''); const handleChange = (event) => { // Update the ref without causing a re-render inputValueRef.current = event.target.value; // Update state to trigger a re-render setInputValue(event.target.value); }; return ( <div> <input value={inputValue} onChange={handleChange} /> <p>Input value (using ref): {inputValueRef.current}</p> </div> ); } export default MyComponent;

In this example, the ref is used to store the input value without causing a re-render, while the state is used for rendering purposes.