- What is
useRefin React?
- Answer:
useRefis 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
useRefanduseState?
-
useStatetriggers re-renders when updated. -
useRefdoes not trigger re-renders when.currentchanges.
- When should you use
useRefinstead ofuseState?
-
When you want to store values that:
- Don’t affect rendering.
- Should persist between renders (like timers, previous values, DOM references).
- How does
useRefhelp in accessing the DOM?
-
useRefstores 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
useRefvalue? Does the component re-render?
- No. Updating
.currentdoes not cause re-render.
- Difference between
useRefandcreateRef?
-
createRefis re-created on each render (used in class components). -
useRefpersists the same object between renders.
- Can
useRefbe used to store previous state values?
- Yes, by manually updating
.currentinsideuseEffect.
- Can you pass
useRefbetween components?
- Yes, but usually with
forwardRefto expose refs from child to parent.
- What is the initial value of a
useRefobject?
- Whatever you pass inside
useRef(initialValue)→ stored in.current.
- Why is
useRefcalled 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)