- What is
useRef
in React?
- Answer:
useRef
is a React hook that returns a mutable object (.current
) whose value persists across re-renders. - Example:
const myRef = useRef(null);
- What’s the difference between
useRef
anduseState
?
-
useState
triggers re-renders when updated. -
useRef
does not trigger re-renders when.current
changes.
- When should you use
useRef
instead ofuseState
?
-
When you want to store values that:
- Don’t affect rendering.
- Should persist between renders (like timers, previous values, DOM references).
- How does
useRef
help in accessing the DOM?
-
useRef
stores a reference to a DOM element that you can access directly. - Example:
myRef.current.focus()
to focus an input.
- What happens if you update a
useRef
value? Does the component re-render?
- No. Updating
.current
does not cause re-render.
- Difference between
useRef
andcreateRef
?
-
createRef
is re-created on each render (used in class components). -
useRef
persists the same object between renders.
- Can
useRef
be used to store previous state values?
- Yes, by manually updating
.current
insideuseEffect
.
- Can you pass
useRef
between components?
- Yes, but usually with
forwardRef
to expose refs from child to parent.
- What is the initial value of a
useRef
object?
- Whatever you pass inside
useRef(initialValue)
→ stored in.current
.
- Why is
useRef
called a “box” object in React docs?
* Because `.current` acts like a box where you put a value and retrieve it without triggering re-renders.
Top comments (0)