1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. Useref Hook
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
00Hrs
19Mins
42Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. Useref Hook

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
00Hrs
19Mins
42Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

useRef Hook

Overview

While useState is perfect for data that should trigger a visual re-render when it changes (like a counter or a toggled menu), sometimes you need to store data that changes without triggering a re-render. This is where `useRef` comes in.

useRef is essentially a 'secret pocket' for your component. It returns a mutable object with a single property: .current. You can store any value in this property (numbers, strings, objects). When you update ref.current, React completely ignores the change and does NOT re-render the component.

useRef has two primary use cases: 1. Holding mutable values that shouldn't affect the UI (like storing a setInterval ID so you can clear it later, or tracking how many times a component has rendered). 2. Direct DOM Access: React is declarative, meaning you usually let React handle the DOM. But sometimes you must access a raw HTML element directly (e.g., to focus an <input>, or draw on a <canvas>). You can pass a ref to the ref attribute of an HTML tag, and React will assign that raw DOM node to ref.current.

Syntax

Use Case 1: Direct DOM Access
javascript
import { useRef } from 'react';

function CustomInput() {
  // 1. Create a ref initialized to null
  const inputRef = useRef(null);

  const focusInput = () => {
    // 3. Access the raw HTML DOM node and call native methods on it
    inputRef.current.focus();
    inputRef.current.style.backgroundColor = 'yellow';
  };

  return (
    <div>
      {/* 2. Attach the ref to the element using the special 'ref' prop */}
      <input ref={inputRef} type="text" placeholder="Type here..." />
      <button onClick={focusInput}>Focus the Input</button>
    </div>
  );
}
Use Case 2: Storing Mutable Values (No Re-Renders)
javascript
function Stopwatch() {
  const [time, setTime] = useState(0);
  // We need to store the interval ID so we can stop it later.
  // If we used useState, storing the ID would cause a useless re-render.
  const timerId = useRef(null);

  const start = () => {
    // Mutating .current does NOT trigger a re-render
    timerId.current = setInterval(() => setTime(t => t + 1), 1000);
  };

  const stop = () => {
    clearInterval(timerId.current);
  };

  return ( /* ... */ );
}

Common Pitfalls

  • Displaying ref values in JSX: Do not write <h1>{myRef.current}</h1>. Because updating a ref does not trigger a re-render, if the ref value changes from 1 to 2, the screen will still display 1 until something else (like a state change) forces the component to re-render. Only use useState for data displayed on the screen.

Interview Questions

What is the difference between useState and useRef?

useState causes the component to re-render when the value changes. It is meant for data that affects the visual UI. useRef does NOT cause a re-render when its value changes. It is used to store mutable data behind the scenes or to hold references to direct HTML DOM nodes.

Why does useRef return an object { current: value } instead of just the value directly?

By returning a consistent object reference, React ensures that the variable points to the exact same location in memory across all re-renders. If you mutate the .current property, the memory address of the object itself doesn't change, allowing the value to persist across render cycles without triggering React's diffing engine.

Real-World Example

Tracking Previous State: This is a classic senior-level pattern. Because refs are synchronous and persist across renders, you can use them to 'remember' what a prop or state variable was during the previous render cycle, allowing you to calculate trends or diffs.

example
javascript
function PriceTracker({ currentPrice }) {
  // We want to know if the price went up or down compared to yesterday.
  const prevPriceRef = useRef(currentPrice);

  useEffect(() => {
    // After every render, we update the ref to hold the current price.
    // Because this happens AFTER the render, during the next render,
    // the ref will still hold the OLD price!
    prevPriceRef.current = currentPrice;
  }, [currentPrice]);

  const prevPrice = prevPriceRef.current;
  const trend = currentPrice > prevPrice ? '🟢 Up' : '🔴 Down';

  return (
    <div>
      <h2>Current: ${currentPrice}</h2>
      <p>Trend: {trend}</p>
    </div>
  );
}

Check Your Knowledge

Test your understanding of useRef Hook with these quick questions.

Question 1

Which of the following scenarios is the correct use case for `useRef`?

Question 2

What happens when you reassign the `.current` property of a ref?

Take React Quiz
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

useRef Hook

Overview

While useState is perfect for data that should trigger a visual re-render when it changes (like a counter or a toggled menu), sometimes you need to store data that changes without triggering a re-render. This is where `useRef` comes in.

useRef is essentially a 'secret pocket' for your component. It returns a mutable object with a single property: .current. You can store any value in this property (numbers, strings, objects). When you update ref.current, React completely ignores the change and does NOT re-render the component.

useRef has two primary use cases: 1. Holding mutable values that shouldn't affect the UI (like storing a setInterval ID so you can clear it later, or tracking how many times a component has rendered). 2. Direct DOM Access: React is declarative, meaning you usually let React handle the DOM. But sometimes you must access a raw HTML element directly (e.g., to focus an <input>, or draw on a <canvas>). You can pass a ref to the ref attribute of an HTML tag, and React will assign that raw DOM node to ref.current.

Syntax

Use Case 1: Direct DOM Access
javascript
import { useRef } from 'react';

function CustomInput() {
  // 1. Create a ref initialized to null
  const inputRef = useRef(null);

  const focusInput = () => {
    // 3. Access the raw HTML DOM node and call native methods on it
    inputRef.current.focus();
    inputRef.current.style.backgroundColor = 'yellow';
  };

  return (
    <div>
      {/* 2. Attach the ref to the element using the special 'ref' prop */}
      <input ref={inputRef} type="text" placeholder="Type here..." />
      <button onClick={focusInput}>Focus the Input</button>
    </div>
  );
}
Use Case 2: Storing Mutable Values (No Re-Renders)
javascript
function Stopwatch() {
  const [time, setTime] = useState(0);
  // We need to store the interval ID so we can stop it later.
  // If we used useState, storing the ID would cause a useless re-render.
  const timerId = useRef(null);

  const start = () => {
    // Mutating .current does NOT trigger a re-render
    timerId.current = setInterval(() => setTime(t => t + 1), 1000);
  };

  const stop = () => {
    clearInterval(timerId.current);
  };

  return ( /* ... */ );
}

Common Pitfalls

  • Displaying ref values in JSX: Do not write <h1>{myRef.current}</h1>. Because updating a ref does not trigger a re-render, if the ref value changes from 1 to 2, the screen will still display 1 until something else (like a state change) forces the component to re-render. Only use useState for data displayed on the screen.

Interview Questions

What is the difference between useState and useRef?

useState causes the component to re-render when the value changes. It is meant for data that affects the visual UI. useRef does NOT cause a re-render when its value changes. It is used to store mutable data behind the scenes or to hold references to direct HTML DOM nodes.

Why does useRef return an object { current: value } instead of just the value directly?

By returning a consistent object reference, React ensures that the variable points to the exact same location in memory across all re-renders. If you mutate the .current property, the memory address of the object itself doesn't change, allowing the value to persist across render cycles without triggering React's diffing engine.

Real-World Example

Tracking Previous State: This is a classic senior-level pattern. Because refs are synchronous and persist across renders, you can use them to 'remember' what a prop or state variable was during the previous render cycle, allowing you to calculate trends or diffs.

example
javascript
function PriceTracker({ currentPrice }) {
  // We want to know if the price went up or down compared to yesterday.
  const prevPriceRef = useRef(currentPrice);

  useEffect(() => {
    // After every render, we update the ref to hold the current price.
    // Because this happens AFTER the render, during the next render,
    // the ref will still hold the OLD price!
    prevPriceRef.current = currentPrice;
  }, [currentPrice]);

  const prevPrice = prevPriceRef.current;
  const trend = currentPrice > prevPrice ? '🟢 Up' : '🔴 Down';

  return (
    <div>
      <h2>Current: ${currentPrice}</h2>
      <p>Trend: {trend}</p>
    </div>
  );
}

Check Your Knowledge

Test your understanding of useRef Hook with these quick questions.

Question 1

Which of the following scenarios is the correct use case for `useRef`?

Question 2

What happens when you reassign the `.current` property of a ref?

Take React Quiz

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A