Q1. What is the useRef hook?
useRef returns a mutable ref object whose .current property is initialized to the passed argument. The object persists for the full lifetime of the component. It's commonly used to access DOM elements directly or to store mutable values that don't cause re-renders when updated.
Q2. How do you use useRef to access a DOM element?
Create a ref with useRef and attach it to an element via the ref attribute. Example: const inputRef = useRef(null); return . Then you can focus the input: inputRef.current.focus().
Q3. How is useRef different from useState?
Updating a ref does not trigger a re-render, while updating state does. refs are used for values that don't affect the UI, like interval IDs or previous state values. useState is for data that should cause re-renders.
Q4. Can you store a previous state value using useRef?
Yes, you can use a ref to hold the previous state by updating it in useEffect after each render. For example: const prevCount = useRef(); useEffect(() => { prevCount.current = count; }, [count]);
Q5. What are some common use cases for useRef?
Focusing inputs, integrating with third-party DOM libraries, storing mutable values like timers, and keeping references to previous props or state to compare.
