React JS React Hooks Use Ref

React Refs are a useful feature that act as a means to reference a DOM element or a function component from within a parent component.

We can get more idea by looking below example. you can put this file in /src/components folder and put in /src/App.js file.

1. RefHookReact

RefHookReact
import React, {useEffect, useRef} from 'react'; function RefHookReact { const inputRef = useRef(null); useEffect(() => { console.log(inputRef); inputRef.current.focus(); },[]) return( <div> <input type='text' ref={inputRef} /> </div> ); } export default RefHookReact;

In above code, We create an object of useRef and assign it to inputRef. now inputRef given to input element ref. and In useEffect we write code that focus on textbox. While running this code, It will show focused on textbox and one object in console panel.

another example is as per below code.

Example
import React, {useEffect, useRef} from 'react'; function RefHookReact { const intervalRef = useRef(); const [timer, setTimer] = useState(0); useEffect(() => { intervalRef.current = setInterval(() => { setTimer(prevTimer => prevTimer + 1) }, 1000) return ()=> { clearInterval(intervalRef.current); } },[]) return( <div> Hook Timer - {timer} <button onClick={() => clearInterval(intervalRef.current)} >Clear Hook Interval</button> </div> ); } export default RefHookReact;

In above code, useRef used to create a generic container that can hold a muteable value similars to instance property on a class component. when we click on button it will clear interval and increment of count is stopped.

 

← Previous

Next →