Day 13 of 50 Days of React: useRef Hook in React.

Aman Khan
2 min readJul 28, 2022

--

What is useRef Hook📎 in React?

  • The useRef hook allows you to persist value between renders🔁.
  • It can be used to store🏬 a mutable value that does not cause a re-render when updated.
  • It can be used to access a DOM element directly.

Does not cause Re-renders🙂

If we tried to count how many times our application re-renders using the useState Hook, we would be caught in an infinite loop since the hook itself causes re-renders.

To avoid, these we can use the useRef Hook.

import { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom/client";
function App() {
const [inputValue, setInputValue] = useState("");
const count = useRef(0);
useEffect(() => {
count.current = count.current + 1;
});
return (
<>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<h1>Render Count: {count.current}</h1>
</>
);
}

useRef only returns one item. It returns an Object called current⚡.

When we initialize useRef we set the value : useRef(0)

It's like doing this: const count = {current: 0}.
We can access the count by using count.current.

Accessing the DOM elements😯

In general, we want to let React handle all DOM manipulation.

But there are some instances where useRef can be used without causing issues.

In React, we can add a ref attribute to an element to access it directly in the DOM.

import { useRef } from "react";
import ReactDOM from "react-dom/client";
function App() {
const inputElement = useRef();
const focusInput = () => {
inputElement.current.focus();
};
return (
<>
<input type="text" ref={inputElement} />
<button onClick={focusInput}>Focus Input</button>
</>
);
}

Tracking state changes🤨

The useRef Hook can also be used to keep track of previous state values.

This is because we are able to persist useRef values between renders.

import { useState, useEffect, useRef } from "react";
import {ReactDOM} from "react-dom";
function App() {
const [inputValue, setInputValue] = useState("");
const previousInputValue = useRef("");
useEffect(() => {
previousInputValue.current = inputValue;
}, [inputValue]);
return (
<>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<h2>Current Value: {inputValue}</h2>
<h2>Previous Value: {previousInputValue.current}</h2>
</>
);
}

In the next article I will be writing about useReducer Hook🤔 ?

That’s all for Today, Stay Tuned and I will see you in the next one👋🏻.

Thanks for Following and Claps😋

Link to Day 14

Link to Starter Page

--

--

Aman Khan

Blockchain and Web3 Engineer Crafting compelling stories at the intersection of tech, business, and culture.