useRef is a React Hook that provides a mutable object called a ref object. Refs are primarily used to interact with the DOM or to persist values across renders without causing re-renders.
`useRef` Hook gives direct access to manipulate DOM elements, manage timers, store mutable values, or preserve values across component re-renders without causing re-renders.
Updating a `useRef` does not trigger a re-render. unlike useState, useContext Hooks.
`useRef` can be used to manage focus, control text selection, and interact with react elements efficiently.
React useRef Hook enhances the performance of the application by preventing unnecessary re-renders when updating the `ref` value.
the `inputRef` attribute is used to create a reference to the input element. `inputRef.current.focus()` function `autoFocus input field` first-time component rendered in DOM.
import React, { useRef, useEffect } from 'react'; const InputComponent = () => { // Initialize useRef Hook const inputRef = useRef(null); useEffect(() => { // Focus on the input element when the component mounts inputRef.current.focus(); }, []); return <input ref={inputRef} type="text" />; }; export default InputComponent;
The useEffect hook ensures that the input element receives focus when the component mounts.
`countRef` is used to persist the `count` value across renders without causing a re-render. The count state is updated only when necessary.
import React, { useRef, useState } from 'react'; const YourCounterComponent = () => { const countRef = useRef(0); const [count, setCount] = useState(0); const increment = () => { countRef.current += 1; setCount(countRef.current); }; return ( <div> <p>Count: {count}</p> <button onClick={increment}>Increment</button> </div> ); }; export default YourCounterComponent;
Update useRef with setInterval in Functional Component.
when the component renders first in DOM, the `useEffect` hook function gets invoked and it will call the setInterval function after each second, and we are clearing the `setInterval` instance using the `clearInterval` function. when the page URL changes or the component is removed from DOM. During the execution of `setInterval`, it will update the `ref` current value and `timeValue` state as well.
import React, { useRef, useEffect, useState } from 'react'; const YourTimerComponent = () => { const [timeValue, setTimeValue] = useState(0) const seconds = useRef(0); useEffect(() => { const intervalId = setInterval(() => { seconds.current += 1; setTimeValue(seconds.current); console.log('Seconds:', seconds.current); }, 1000); return () => clearInterval(intervalId); }, []); const timerStatus = `Timer is running from ${timeValue} secs` return <p>{timerStatus}</p>; }; export default YourTimerComponent;
`seconds` is a useRef value to store and update the elapsed time. The value of the ref persists across renders without causing re-renders.