What is useRef for?
Options
- A mutable value or DOM node that does not re-render (Correct option)
- To store state that triggers a re-render of the UI
- To fetch data from an API when the component loads
- To define the CSS styles of a component in React
Answer
Holding a mutable value or a reference to a DOM element that persists across renders without causing a re-render when it changes
Why
useRef(initial) returns an object { current: ... } that React keeps between renders. Changing current does NOT re-render.
Uses: focusing an input (inputRef.current.focus()), storing a timer id, remembering the previous value, any mutable value that is not part of what the screen shows.
If the screen must update when the value changes, use useState instead.
Remember
useRef = persistent box, no re-render on change.