DEV Community

Dinesh G
Dinesh G

Posted on

UseRef in React JS

Use Ref:

Default UseState

What:

Use Ref is a React hook that lets you a Value that is not needed for re-rendering mutable returning Singles Current property.
ref (short for reference) is a special tool that lets you directly access and Control Dom elements.

Why. Use Ref

  • Focusing or selecting an input field
  • Scrolling to a section of the page
  • Playing or pausing video
  • Using third-party libraries (charts, animations, etc)
  • Ref gives you direct control over elements

When:

  • When you need to access or change the DOM directly
  • When you want to store a value across renders but don't want to trigger a re-render.
  • When using imperative actions (focus, scroll, animation, etc).
import React, { useRef, useEffect } from 'react';

function TextInputWithFocusButton() {
  // 1. Create a ref to hold the input DOM element
  const inputEl = useRef(null);

  // Example: Focus on initial mount 
  useEffect(() => {
    inputEl.current?.focus();     
  }, []);                 
  // Empty dependency array means run once after initial mount

  return (
    <>
      {/* 2. Attach the ref to the input element */}
      <input ref={inputEl} type="text" />
    </>
  );
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)