UseRef Hooks

import React, { useRef } from "react";

const CustomTextInput = () => {
  const textInput = useRef();

  focusTextInput = () => textInput.current.focus();

  return (
    <>
      <input type="text" ref={textInput} />
      <button onClick={focusTextInput}>Focus the text input</button>
    </>
  );
}
  • In class components In the component state: Every time the state changes, the component will be re-rendered.

  • In an instance variable: The variable will persist for the full lifetime of the component. Changes in an instance variable won’t generate a re-render. In functional components

  • The equivalent ways in functional components using Hooks: In a state variable: useState or useReducer. Updates in state variables will cause a re-render of the component.

  • In a ref: Equivalent to instance variables in class components. Mutating the .current property won’t cause a re-render.
import React, { useRef, useEffect } from "react";

const Timer = () => {
  const intervalRef = useRef();

  useEffect(() => {
    const id = setInterval(() => {
      console.log("A second has passed");
    }, 1000);

    // We need the interval id to be accessible from the whole component.
    // If we stored the id in a state variable, the component would be re-rendered
    // after the state update so a new interval will be created (this effect is triggered
    // after every re-render) leading us to the infinite loop hell.
    intervalRef.current = id;

    return () => clearInterval(intervalRef.current);
  });

  const handleCancel = () => clearInterval(intervalRef.current);

  return (
    <>
      //...
    </>
  );
}
import React, { useRef,useEffect } from "react";

 const App = () => {
  const counter = useRef(0);

  useEffect(() => {
    // Every time the component has been re-rendered,
    // the counter is incremented
    counter.current = counter.current + 1;
  }); 

  return (
    <h1>{`The component has been re-rendered ${counter} times`}</h1>
  );
};

export default App;