useRef 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!!