How to use useRef() hook In ReactJS
We cannot use the ref attribute in the functional components because they don’t have the instances. To use the ref functionality in the functional component we can use the useRef hook.
- Create a ref variable using React.useRef()
- Attach ref variable to the React element by using the ref attribute of the element.
- The benefit of using useRef() over createRef() is that it’s handy for keeping any mutable value around similar to how you’d use instance fields in classes.
- The useRef() also takes an initial value.
Syntax:
const func = useRef(null);
What is significance of refs in ReactJS ?
Refs are a function provided by React to access the DOM element and the React element that you might have created on your own. They are used in cases where we want to change the value of a child component, without making use of props and all. They also provide us with good functionality as we can use callbacks with them. We can create a Ref by the following three methods:
Table of Content
- Using React.createRef()
- Using useRef() hook
- Using callback ref
- Significance of Refs in React JS: