Skip to content
Node.js Sounds Complicated? This Article Makes It Click

React useRef Explained – How to Use Ref Hooks in Components

The React Ref Hook lets you store values that don’t trigger re-renders when changed.

This guide provides a concise overview of key React Ref Hook concepts, helping you quickly grasp the essentials before diving deeper.

RefStateVariable
Value persists during re-renderingYesYesNo
Updating value triggers re-renderingNoYesNo
It’s plain JavaScriptYesNoYes
Declarable outside componentsNoNoYes
Usable in conditions, loops, or nested functionsNoNoYes

The useRef Hook accepts only one optional argument. Here is the syntax:

useRef(initialValue);
  • initialValue: The value to store in the component’s ref memory. Any JavaScript data type is allowed.
  • useRef(): Returns an object ({ current: initialValue }).
import { useRef } from "react";
function App() {
const myNameRef = useRef("Oluwatobi");
function handleClick() {
console.log(myNameRef.current); // Outputs: "Oluwatobi"
}
return <button onClick={handleClick}>Click me</button>;
}
export default App;

Try it on CodeSandbox

The snippet above used the useRef Hook to store a value ("Oluwatobi") whose update shouldn’t trigger re-renders.

  • Use dot syntax to access and update a ref object’s value instead of square bracket notation.
  • Avoid accessing or updating the current property during rendering to maintain the purity of your components.
  • Don’t use a function instance as your initialValue. Pass the function itself, not its output.
  • You can use the React Ref Hook to manage your HTML DOM nodes.

The Code React Sweetly book guides you through all aspects of using the React Ref Hook, including:

  • What is useRef? – Understand its core purpose
  • Ref vs. State vs. Variable – Avoid common mistakes
  • How to access & update ref values – Practical examples
  • Managing DOM nodes – Step-by-step guide
  • Behind-the-scenes mechanics – How refs really work

A Beginner's Guide to React: Learn JSX, Hooks, and Real-World App Development