Using React Refs and useRef Hook
React uses a declarative approach. You update state, and React updates the UI. This works for most tasks.
But sometimes you need to step outside the Virtual DOM. You might need to touch a real HTML element directly. This is where Refs and the useRef hook come in.
What is a Ref? A Ref is a pointer. It connects React directly to a native DOM node.
Why use useRef instead of useState? State updates trigger a re-render. This means React redraws the component on the screen. Ref updates do not trigger a re-render. This makes them perfect for values that change but do not need to show up in the UI immediately.
Common use cases: • Focusing an input field automatically. • Controlling video or audio elements (play/pause). • Measuring the width or height of an element. • Storing timer IDs for intervals or timeouts.
How to use useRef:
- Import useRef from React.
- Initialize it: const myRef = useRef(null).
- Attach it to an element: .
- Access the value via: myRef.current.
Example 1: Auto-focusing an input When a user enters a page, you want the cursor to be in the text box. You use useEffect to call myRef.current.focus() after the component mounts.
Example 2: A Stopwatch If you store a setInterval ID in state, the component re-renders every time the timer ticks. This is slow. If you store the ID in a ref, the component stays fast. The value stays safe across renders without causing extra work for the browser.
State vs Ref: • State: Triggers re-render. Used for UI data. Updates are asynchronous. • Ref: No re-render. Used for DOM access and memory. Updates are synchronous.
Pro Tips for Seniors: • Avoid overuse. Only use refs when declarative logic fails. • Clean up memory. Always clear intervals or event listeners in your cleanup function. • Do not write to refs during rendering. Only update ref.current inside useEffect or event handlers. This prevents side effects. • Use forwardRef. If you want to pass a ref to a custom child component, you must wrap that child in React.forwardRef.
Source: https://dev.to/banti_kevat_8e2d123bb7994/react-me-refs-aur-useref-hook-kaise-use-karein-2dde
