useRef in React Js | React Js for Beginners

I am sure you guys have used jQuery , over Java Script. Have you seen how jQuery drastically reduces the lines of code. The things which can be done on java script with 5 line, jquery does it in a single line. A something similar can be achived with the help of useRef(). Well , keeping that in mind , lets get started.

Watch Video

Basic Syntax

Dont worry about they syntax, it will make more sense as we proceed.

const refContainer = useRef(initialValue);

The reference changes according to which element it has been placed –

Eg - 

const h1Ref = useRef();

 <h1 ref={h1Ref} className="xyz">
        Hello
      </h1>

console.log("output",h1Ref.current)

output -
------
output <h1 class="xyz">

Well , here is the example which I was talking about. Just have a bird eye view, no need to go deep into it.

Important points about useRef

  • 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.
  • useEffect always return an mutable ref object with a single property “current
  • A hook that allows to directly create a reference to the DOM element
  • Its not relevant to store value and do other things with useRef() because useState is already designed for that

Practical use case of useRef() hook

Now let’s see the code and understand where useRef is being used

Mutating a value does not cause re-render

Here in this example, we can easily see that we are changing the value of state and ref.current , but only state value is updating on every click, it because useRef does not re-render the page when the value is mutated.

This simply proves that useRef is not use in such condition . At such place , useState in preferred

//mutating a value does not cause re-render
import React, { useEffect, useRef, useState } from "react";
import "../App.css";

const CompB = () => {
  const [first, setfirst] = useState(34);

  const inputRef = useRef(4);

  function incState() {
    setfirst(first + 1);
    console.log("first", first);
  }
  function incRef() {
    inputRef.current += 1;
    console.log(inputRef.current);
  }

  return (
    <div>
      <h1>hello</h1>
      <p>{first}</p>
      <p>{inputRef.current}</p>
      <button onClick={incState}>Inc State</button>
      <button onClick={incRef}>Inc Ref</button>
    </div>
  );
};

export default CompB;

Allows to directly create a reference to the DOM element

import React, { useEffect, useRef, useState } from "react";

const LearnUseRef = () => {
  const inputRef = useRef();


  function incValue() {
    console.log("inc me", inputRef.current);
    inputRef.current.focus();
    // inputRef.current.style.background = "red";
    // inputRef.current.className = "";
    inputRef.current.classList.remove("redMe");
    inputRef.current.classList.add("greenMe");
    console.log("inc me", inputRef.current);
  }

  console.log(inputRef);

  return (
    <div className="App-header">
      <input
        type="text"
        placeholder="type here..."
        className="redMe"
        ref={inputRef}
      />
   
      <button onClick={incValue}>Increase Me</button>
    </div>
  );
};

export default LearnUseRef;

useRef() is not a useState replacement or alternative

I hope now its somewhat clear that useRef is mainly used when you need to reference an element and play around with its attribute, but when is comes to handling data side ,let’s leave it to useState and useEffect.

Help Others

Himanshu Shekhar

Hey. I am a software engineer with 3+ years. Along with my job, I create content regarding coding and software engineering in general. I would request you to follow my blog and my video, which will help you in your software engineering journey. Follow me on Youtube →
View All Articles

Leave a Reply

Your email address will not be published.