Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
ReactJS useRef Hook
Next article icon

ReactJS useRef Hook

Last Updated : 08 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The useRef Hook is a built-in React Hook that returns a mutable reference object (ref) that persists across renders. Unlike state variables, updating a ref does not trigger a component re-render.

Syntax

const refContainer = useRef(initialValue);
  • useRef returns an object { current: initialValue }.
  • The .current property can be updated without re-rendering the component.

Implementing the useRef hook

1. Accessing the DOM using useRef hook.

In this example, we have a button called ACTION, whenever we click on the button the onClickHandler gets triggered and it focuses the textarea with the help of useRef hook.

JavaScript
import React, { Fragment, useRef } from 'react';  function App() {     const focusPoint = useRef(null);     const onClickHandler = () => {         focusPoint.current.value =             "The quick brown fox jumps over the lazy dog";         focusPoint.current.focus();     };     return (         <Fragment>             <div>                 <button onClick={onClickHandler}>                     ACTION                 </button>             </div>             <label>                 Click on the action button to                 focus and populate the text.             </label><br />             <textarea ref={focusPoint} />         </Fragment>     ); }; export default App; 

Output

React JS useRef Hook

In this example

  • useRef creates a reference focusPoint, which allows direct manipulation of the DOM element.
  • Clicking the "ACTION" button triggers onClickHandler, which sets text in the textarea and focuses it.
  • <Fragment> (<>...</>) is used to group multiple elements without adding extra wrappers in the DOM.

2. Persisting Values Across Renders

In addition to accessing DOM elements, useRef is useful for storing values that persist across renders. A common use case is storing a previous value, such as the previous state or props.

JavaScript
import React, { useState, useRef, useEffect } from "react"; function PreviousValue() {     const [count, setCount] = useState(0);     const prevCountRef = useRef();      useEffect(() => {         prevCountRef.current = count;     }, [count]);      return (         <div>             <p>Current count: {count}</p>             <p>Previous count: {prevCountRef.current}</p>             <button onClick={() => setCount(count + 1)}>Increment</button>         </div>     ); } export default PreviousValue; 

Output

Increment-operator
Persisting Values Across Renders

In this example

  • count is a state variable that tracks the current count.
  • prevCountRef is a reference created with useRef to store the previous count value.
  • Whenever count changes, the useEffect hook updates prevCountRef.current to store the previous count.
  • Clicking the button increases the count by 1 and updates both the current and previous counts.

Interesting Things About useRef Hook

  • Does Not Cause Re-renders: Unlike state variables, updating a useRef value does not trigger a component re-render. This makes it useful for storing values that persist across renders without causing unnecessary updates.
  • Accessing DOM Elements: useRef is commonly used to reference DOM elements directly, allowing operations such as focusing input fields, managing animations, and interacting with elements without causing re-renders.
  • Tracking State Changes: It can be used to store previous state values and track changes between renders, which is helpful for comparing current and previous values without affecting component updates.

When to Use useRef?

You should use useRef when

  • Accessing and manipulating DOM elements without triggering re-renders.
  • Persisting values across renders without causing re-renders.
  • Storing previous state values to compare changes between renders.
  • Optimizing performance by avoiding unnecessary state updates.

useRef vs useState

While both useRef and useState can store values, they behave differently:

  • useRef does not trigger re-renders when updated, making it ideal for persisting values between renders.
  • useState triggers re-renders whenever the state value is updated.
  • Use useRef for storing references and preserving values, and useState for UI updates.

Performance Considerations

Using useRef correctly can enhance performance, but excessive use may introduce unnecessary complexity.

  • Use it for non-rendered values: Ideal for persisting values like timers, previous states, or DOM elements.
  • Avoid using it as state replacement: If UI updates are needed, use useState instead.
  • Measure before optimizing: Use React DevTools to analyze performance.

Next Article
ReactJS useRef Hook

A

ashisholism
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • React-Hooks

Similar Reads

    ReactJS useEffect Hook
    The useEffect hook is one of the most commonly used hooks in ReactJS used to handle side effects in functional components. Before hooks, these kinds of tasks were only possible in class components through lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.What is
    4 min read
    ReactJS useReducer Hook
    The useReducer hook is an alternative to the useState hook that is preferred when you have complex state logic. It is useful when the state transitions depend on previous state values or when you need to handle actions that can update the state differently.Syntaxconst [state, dispatch] = useReducer(
    5 min read
    ReactJS useId Hook
    React useId Hook is introduced for the ReactJS versions above 18. This hook generates unique IDs i.e, returns a string that is stable across both the server and the client sides. Prerequisite: Introduction and installation of ReactJSReact Hooks Syntax: const id = useId() Creating React Application:
    3 min read
    ReactJS useSelect hook
    The useSelect is a custom hook provided by the Rooks package for React. It is a list selection hook that helps select values from a list. Arguments: list: It is of the type array which describes the list of items for the selection. The default value is undefined.initialIndex -It is of the type numbe
    2 min read
    ReactJS useContext Hook
    In React Applications, sometimes managing state across deeply nested components can become very difficult. The useContext hook offers a simple and efficient solution to share state between components without the need for prop drilling.What is useContext Hook?The useContext hook in React allows compo
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences