Q1. What is useRef in React?
useRef is a React Hook used to store a value that persists between renders without causing a component to re-render when that value changes.
It is commonly used for:
- Accessing DOM elements.
- Storing previous values.
- Managing timers.
- Keeping mutable values between renders.
const ref = useRef(initialValue); Q2. What does useRef return?
It returns a mutable object with a current property.
const myRef = useRef(10); console.log(myRef.current); // 10 We can update it:
myRef.current = 20; console.log(myRef.current); // 20 Updating current does not trigger a component re-render.
Q3. What is the difference between useState and useRef?
const [count, setCount] = useState(0); const countRef = useRef(0); setCount(count + 1); // Re-render countRef.current++; // No re-render Q4. How can you access a DOM element using useRef?
import { useRef } from 'react'; function App() { const inputRef = useRef(null); const handleClick = () => { inputRef.current.focus(); }; return ( <> <input ref={inputRef} placeholder="Enter your name" /> <button onClick={handleClick}> Focus Input </button> </> ); } export default App; Explanation:
- useRef(null) creates a ref object.
- ref={inputRef} connects the ref to the input element.
- inputRef.current refers to the actual DOM input element.
- focus() is a DOM method used to focus the input.
Q5. Can we store previous values using useRef?
Yes. We can use useRef to store the previous value.
import { useEffect, useRef, useState } from 'react'; function App() { const [count, setCount] = useState(0); const previousCount = useRef(); useEffect(() => { previousCount.current = count; }, [count]); return ( <> <h1>Current: {count}</h1> <h2>Previous: {previousCount.current}</h2> <button onClick={() => setCount(count + 1)}> Increment </button> </> ); } Here:
- count stores the current value.
- previousCount.current stores the previous value.
- The effect updates the ref after the current render is committed.
