Home
Basics
Introduction Setting up environment First Component JSX Component lifecycle Class Based Components Function Based Components Props State Hooks useState hook useEffect hook Events Server requests CSS in React Router third party JavaScriptAdvanced
useContext hook useRef hook useReducer hook Memo useCallback hook Custom Hooks React and ReduxMiscellaneous
React Third Party Components Html templates in React React Interview QnAuseRef hook in React
useRef hook is used to store and update references. It does not trigger component re-render when the ref changes. That's the main difference between useRef and useState. Everytime you change the state, component is re-renderd but that's not the case with useRef. In below example, component will not rerender even if you click button 3 times. It will only render after you click 4th time.That's because even though reference current value is changing, setState is not getting called till 3 clicks.
import { useRef, useState } from "react";
function CountButtonClicks() {
const countRef = useRef(0);
const [count, setCount] = useState(0);
const clickHandler = () => {
countRef.current++;
console.log("Button Click Counter ", countRef.current );
if (countRef.current >= 4) {
setCount(countRef.current);
}
};
console.log("Render triggered!!");
return <button onClick={clickHandler}>Click me {count}</button>;
}
export default CountButtonClicks;
Accessing DOM elements
Another use case of useRef is to access DOM elements. Traditionally we use document.getElementById or querySelector methods to access DOM elements. But in react, we need to use useRef hook. Below example shows how to use useRef hook to focus on input element.
import { useRef, useEffect } from "react";
function focusInputElement() {
const inputRef = useRef();
useEffect(() => {
//focus on input element after component is mounted
inputRef.current.focus();
}, []);
return <input ref={inputRef} type="text" placeholder='name'/>;
}
export default focusInputElement;
Web development and Automation testing
solutions delivered!!