DEV Community

FatimaAlam1234
FatimaAlam1234

Posted on

React Refs

Refs

It is short for reference and as the name suggests it is a pointer to a DOM element.

Why do we need Refs?

  1. If there are a lot of states particular to a react component can make it cumbersome so we use Refs instead.
  2. in case of Refs -> unnecessary re-rendering is ruled out because it maintains it's value during re-renders.
  3. In case of validity checking states perform before hand checking as they re-render but refs do that only when the page is submitted.
  4. Whenever we want to focus on for eg. a text field on a clik event, we use Refs to to refer to that input box and focus the field.
  5. Refs can be used both in Class and Functional Component.
  6. In class -> we use React.createRef() an function -> useRef();
  7. React.createRef() has default value null and can't be given while useRef() can be given a default value.

Disadvantage ->
Debugging of Refs is difficult
Refs are generally not recommended.

Top comments (0)