Refs
It is short for reference and as the name suggests it is a pointer to a DOM element.
Why do we need Refs?
- If there are a lot of states particular to a react component can make it cumbersome so we use Refs instead.
- in case of Refs -> unnecessary re-rendering is ruled out because it maintains it's value during re-renders.
- In case of validity checking states perform before hand checking as they re-render but refs do that only when the page is submitted.
- 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.
- Refs can be used both in Class and Functional Component.
- In class -> we use React.createRef() an function -> useRef();
- 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)