DEV Community

swetha palani
swetha palani

Posted on

Useref in react theory question

  1. 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);
  1. What’s the difference between useRef and useState?
  • useState triggers re-renders when updated.
  • useRef does not trigger re-renders when .current changes.
  1. When should you use useRef instead of useState?
  • When you want to store values that:

    • Don’t affect rendering.
    • Should persist between renders (like timers, previous values, DOM references).
  1. 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.
  1. What happens if you update a useRef value? Does the component re-render?
  • No. Updating .current does not cause re-render.
  1. Difference between useRef and createRef?
  • createRef is re-created on each render (used in class components).
  • useRef persists the same object between renders.
  1. Can useRef be used to store previous state values?
  • Yes, by manually updating .current inside useEffect.
  1. Can you pass useRef between components?
  • Yes, but usually with forwardRef to expose refs from child to parent.
  1. What is the initial value of a useRef object?
  • Whatever you pass inside useRef(initialValue) → stored in .current.
  1. 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.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)