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.
Ref vs. State vs. Variable
Section titled “Ref vs. State vs. Variable”| Ref | State | Variable | |
|---|---|---|---|
| Value persists during re-rendering | Yes | Yes | No |
| Updating value triggers re-rendering | No | Yes | No |
| It’s plain JavaScript | Yes | No | Yes |
| Declarable outside components | No | No | Yes |
| Usable in conditions, loops, or nested functions | No | No | Yes |
Syntax
Section titled “Syntax”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 }).
Example
Section titled “Example”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;The snippet above used the useRef Hook to store a value ("Oluwatobi") whose update shouldn’t trigger re-renders.
Best Practice
Section titled “Best Practice”- Use dot syntax to access and update a ref object’s value instead of square bracket notation.
- Avoid accessing or updating the
currentproperty 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.
Dive Deep
Section titled “Dive Deep”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
