What is the React useRef() Hook and how does it work?
The useRef() Hook is a built-in React feature that allows you to persist values between component re-renders. It returns a mutable object with a current property, which can store any value, including DOM elements, functions, or data. Unlike state variables managed by useState, updating ref.current does not trigger a re-render. This makes useRef() ideal for scenarios where you need to store data that doesn't directly affect the UI but is essential for component behavior. Learn more.
What are the main use cases for useRef() in React applications?
useRef() is commonly used for accessing DOM elements, tracking previous values, managing timers and intervals, and building custom Hooks. For example, you can use useRef() to focus an input field on page load, store previous state values for comparison, or keep track of timer IDs without causing re-renders. See practical examples.
How does useRef() compare to useState() and createRef()?
useRef() and useState() both store values in React components, but useRef() does not trigger re-renders when updated, while useState() does. useRef() is ideal for persisting values across renders without affecting the UI. createRef() is designed for class components and creates a new ref object on every re-render, whereas useRef() maintains the same object throughout the component lifecycle in functional components. Read the comparison.
What are the drawbacks of using useRef()?
Drawbacks of useRef() include manual management of updates (since changes do not trigger re-renders), potential memory leaks if refs are not cleaned up, overuse leading to complex code, debugging challenges, and limitations when updating arrays or objects stored in refs. To mitigate these, use useRef() only when necessary and manage UI-related data with state. See mitigation strategies.
How can useRef() be used with content fetched from Hygraph?
useRef() can enhance user interactions with dynamically fetched content from Hygraph by storing references to elements such as images or content blocks. This enables features like lazy loading, smooth scrolling, and interactive components. Additionally, useRef() can cache results of complex queries, reducing load on the CMS and improving performance. Learn more about integration.
Features & Capabilities
What features does Hygraph offer?
Hygraph is a GraphQL-native Headless CMS with features such as Smart Edge Cache for fast content delivery, Content Federation to integrate data from multiple sources, Rich Text SuperPowers for advanced formatting, Custom Roles for granular access control, and Project Backups for data safety. It also provides industry-leading APIs, seamless integrations, and supports advanced localization and workflows for global teams. See all features.
What integrations are available with Hygraph?
Hygraph offers integrations with digital asset management platforms (Aprimo, AWS S3, Bynder, Cloudinary, Mux, Scaleflex Filerobot), hosting and deployment services (Netlify, Vercel), eCommerce platforms (BigCommerce, commercetools, Shopify), localization tools (Lokalise, Crowdin, EasyTranslate, Smartling), personalization and AB testing (Ninetailed), AI tools (AltText.ai), and more. Explore integrations.
Does Hygraph provide APIs for developers?
Yes, Hygraph provides GraphQL Content API for querying and managing content, GraphQL Management API for schema changes, Public API for programmatic access, and supports both REST and GraphQL APIs for seamless integration with external systems. See API documentation.
Where can I find technical documentation for Hygraph?
Comprehensive technical documentation, API references, guides for content workflows, webhooks, and interactive API playgrounds are available at Hygraph Documentation. These resources support both technical and non-technical users in exploring and utilizing Hygraph effectively.
Use Cases & Benefits
Who can benefit from using Hygraph?
Hygraph is designed for developers, IT decision-makers, content creators, project managers, agencies, solution partners, and technology partners. It is valuable for modern software companies, enterprises seeking to modernize, brands scaling across geographies, and organizations re-platforming from legacy solutions. See use cases.
What problems does Hygraph solve for its customers?
Hygraph addresses operational inefficiencies (removing developer bottlenecks, improving workflows), financial challenges (reducing costs, accelerating speed-to-market), and technical issues (simplifying development, resolving schema and cache challenges, enabling editorial autonomy). It helps unify APIs, scale content operations, and deliver seamless digital experiences. Learn more.
What business impact can customers expect from using Hygraph?
Customers report up to 3X faster time-to-market (Komax), 15% higher customer engagement (Samsung), 20% increase in website monetization (AutoWeb), 7X higher content velocity, 125% traffic growth, and 120% more website clicks. Hygraph supports content management across 40+ global markets and 100+ stakeholders. See case studies.
Can you share specific case studies or success stories of customers using Hygraph?
Yes. Komax achieved 3X faster time-to-market and managed 20,000+ product variations across 40+ markets. Samsung saw a 15% increase in customer engagement. Dr. Oetker ensured global consistency with MACH architecture. HolidayCheck improved workflow efficiency by enabling marketers to update content independently. Sennheiser increased e-commerce conversions by 136.7% within 4 months. Stobag improved online revenue share from 15% to 70%. Read more case studies.
What industries are represented in Hygraph's case studies?
Industries include eCommerce (Si Vale, Vision Healthcare), Automotive (AutoWeb), Healthcare & Fitness (Fitfox, Vision Healthcare), Consumer Electronics (Samsung), Media & Publishing (Telenor), Food & Beverage (Dr. Oetker, K+S), Travel & Hospitality (HolidayCheck), Engineering (Komax Group), Government (Statistics Finland), and SaaS (Bellhop). See all industries.
Ease of Use & Implementation
How easy is it to get started with Hygraph?
Hygraph is recognized as the #1 easiest to implement headless CMS. Customers can start building for free with a developer account, and enterprise users can request a demo. The onboarding process includes introduction calls, account provisioning, business and technical kickoffs, and content schema planning. Developers can use a free API playground for immediate hands-on experience. Try Hygraph.
How long does it take to implement Hygraph?
Implementation is fast. For example, Top Villas launched a new project with Hygraph in just 2 months from initial touchpoint to launch. Si Vale's initial implementation phase went smoothly and met aggressive deadlines. See implementation stories.
What feedback have customers given about Hygraph's ease of use?
Customers praise Hygraph's intuitive editor UI, logical structure, and accessibility for non-technical users. The platform is described as super easy to set up and use, with streamlined workflows and customization features. Both technical and non-technical teams find it user-friendly. Read customer feedback.
Support & Training
What customer service and support does Hygraph offer?
Hygraph provides 24/7 support via chat, email, and phone. Enterprise customers benefit from Service Level Agreements (SLAs) with critical issues resolved in less than an hour. Structured onboarding, a dedicated Customer Success Manager, extensive documentation, a community Slack channel, Intercom chat, and training resources (webinars, live streams) are available. See support options.
What training and technical support is available to help customers adopt Hygraph?
Hygraph offers onboarding support (introduction call, account provisioning, business/technical/content kickoffs), comprehensive documentation, regular technical training sessions, webinars, hands-on guidance, and consultation on content strategy, localization, and migrations. 24/7 technical support and community resources are also available. See onboarding resources.
How does Hygraph handle maintenance, upgrades, and troubleshooting?
Hygraph's cloud-based infrastructure handles all maintenance tasks, including server updates, security patches, and performance optimizations. Upgrades are automatic, and troubleshooting is supported by audit logs, monitoring, and performance reporting. 24/7 support and SLAs ensure prompt resolution of issues. Learn more.
Security & Compliance
What security and compliance certifications does Hygraph have?
Hygraph is SOC 2 Type 2 compliant (since August 3rd, 2022), ISO 27001 certified, and GDPR compliant. These certifications ensure enhanced security and adherence to global standards for information security management and data protection. See certifications.
How does Hygraph ensure data security and compliance?
Hygraph uses granular permissions, audit logs, encryption at rest and in transit, SSO integrations, automatic backups, and one-click recovery. Enterprise-grade compliance features include dedicated hosting, custom SLAs, IT security reviews, and penetration testing. Security incidents can be reported, and a public security report is available. View security report.
Customer Proof & Sample Customers
Who are some of Hygraph's customers?
Sample customers include Sennheiser, HolidayCheck, Ancestry, JDE, Dr. Oetker, Ashley Furniture, Lindex, Hairhouse, Komax, Shure, Stobag, Burrow, G2I, Epic Games, Bandai Namco, Gamescom, Leo Vegas, Codecentric, Voi, and Clayton Homes. See customer stories.
Learn how to use React's useRef Hook for DOM manipulation, performance optimization, and more in this in-depth guide.
Written by Motunrayo
on Dec 09, 2024
The useRef Hook is a versatile tool, often overlooked but crucial for managing references, optimizing performance, and interacting directly with the Document Object Model (DOM). While it might not be as widely discussed as useState or useEffect, it plays a pivotal role in many React applications.
This guide will discuss the useRef Hook, its use cases, practical applications, and drawbacks. By the end, you'll be well equipped to leverage its full potential, unlocking new levels of efficiency and control in your React projects.
The useRef() Hook is a built-in React feature that persists values between component re-renders. Unlike state variables managed by useState, values stored in a ref object remain unchanged across renders, making it ideal for scenarios where data doesn't directly affect the UI but is essential for the component's behavior.
When React encounters a useRef() Hook, it returns a plain JavaScript object with a single property: current. This current property stores mutable values, which can be of any type, from simple values like numbers and strings to complex objects, functions, or even references to DOM elements.
React assigns the initial value you define to the current property of the returned reference. React will set the value of the useRef to undefined if you don't provide an initial value. Importantly, you can update this current value directly without triggering a re-render of the component. This can be seen in the snippet below:
import{ useRef }from"react";
functionMyComponent(){
const reference =useRef(true);
console.log(reference.current);// true
}
Also, the returned reference object is mutable. You can update the current value directly, as shown in the snippet below.
Beyond its ability to persist values, the useRef() Hook has several vital roles in React applications:
Accessing DOM elements
Imagine a login page where users need to enter their username and password. To enhance the user experience, you can automatically direct their focus to the username field as soon as the page loads.
To achieve this, use the useRef 's capacity to access rendered DOM elements. This feature returns the referenced DOM element and its properties, providing room for direct manipulations.
import{ useRef, useEffect }from “react”
functionLogin(){
const usernameRef =useRef(null)
useEffect(()=>{
usernameRef.current.focus()
},[])
return(
<>
<form>
<input type="text" ref={usernameRef}/>
</form>
</>
)
}
The above snippet shows a Login component that renders a form with an input field for the user’s username. Also, it defines a username reference with the useRef Hook, which the focus() method is called on. This is executed inside a useEffect Hook, so it runs immediately after the UI finishes loading.
Tracking previous values
By storing the previous value of the input element as a state variable in a ref, you can monitor changes and address them accordingly. This technique is useful for implementing "undo" functionality, creating custom Hooks that need to compare previous and current values, or optimizing performance by preventing unnecessary calculations.
import{ useState, useRef, useEffect }from'react';
functionCounter(){
const[count, setCount]=useState(0);
const previousCountRef =useRef(count);// Store previous count in a ref
In this example, the useRef Hook stores the previous value of the count state variable. Every time the count changes, the useEffect Hook compares the new count to the value stored in the previousCountRef and logs a message to the console if they differ. This way, you can track how the count value evolves over time.
Managing timers and intervals
The useRef simplifies the management of timers and intervals within your components. You can store the timer's ID in a ref, allowing you to start, stop, or reset it as needed without triggering unnecessary re-renders.
import{ useState, useRef, useEffect }from'react';
functionmyTimer(){
const[seconds, setSeconds]=useState(0);
const timerRef =useRef(null);// Ref to store the timer ID
conststartTimer=()=>{
timerRef.current=setInterval(()=>{
setSeconds((prevSeconds)=> prevSeconds +1);
},1000);// Update every second
};
conststopTimer=()=>{
clearInterval(timerRef.current);
};
constresetTimer=()=>{
clearInterval(timerRef.current);
setSeconds(0);
};
// Cleanup function to clear the interval when the component unmounts
useEffect(()=>{
return()=>clearInterval(timerRef.current);
},[]);
return(
<div>
<p>Time elapsed:{seconds} seconds</p>
<button onClick={startTimer}>Start</button>
<button onClick={stopTimer}>Stop</button>
<button onClick={resetTimer}>Reset</button>
</div>
);
}
In this example, a timer component was created using the useState and useRef Hooks. The useState Hook manages the seconds variable, which keeps track of the elapsed time. Meanwhile, useRef stores a reference to the interval ID (timerRef), which is responsible for updating the seconds every 1000 milliseconds (1 second).
The functions startTimer, stopTimer, and resetTimer control the timer's behavior. startTimer starts the interval, stopTimer stops it, and resetTimer resets the elapsed time to zero.
Building custom Hooks
When creating custom Hooks that need to maintain an internal state between renders, useRef becomes an invaluable asset. It enables you to store and update data privately within the Hook, promoting reusability and encapsulation of complex logic.
Imagine having multiple components that are required to maintain their previous state. It will appear too tedious to write this logic individually for every component. To avoid this, create a custom Hook using the useRef Hook as follows:
First, create a Hooks folder and a file usePreviousState.js, then add the following snippet:
import{ useRef, useEffect }from"react";
exportdefaultfunctionusePreviousState(value){
const ref =useRef();
useEffect(()=>{
ref.current= value;
});
return ref.current;
}
In the snippet above, a useRef instance was created, then on every page re-render, assign the value passed to the usePreviousState Hook to the ref.current. Finally, return the value of the ref.current.
To illustrate the custom Hook's utility, let’s revisit the 'tracking previous values' scenario
In the snippet above, all instances of the initial useRef were replaced with the newly created custom Hook. This shows that creating a custom Hook makes it possible to reuse complex logic.
Beyond its DOM manipulation capabilities, useRef shines as a performance enhancer. Imagine you have a computationally intensive task within your component, such as filtering a dataset or performing calculations, re-executing these operations on every render would be wasteful.
Storing values of these calculations within a ref variable using useRef can avoid unnecessary re-computations. Since refs persist across renders without triggering updates, the calculated value remains accessible and doesn't need to be recalculated unless the underlying data changes. Let's look at the example shown below:
import{ useState, useRef, useMemo }from"react";
exportdefaultfunctioncalculationComponent(){
const[inputNumber, setInputNumber]=useState(10);// Initial Calculation number
const calculateResult =useRef(null);// Ref to store the calculated result
constcalculateFib=(n)=>{
if(n <=1)return n;
returncalculateFib(n -1)+calculateFib(n -2);
};
// Memoize the calculation using useMemo
const memoizedCal =useMemo(()=>{
if(
calculateResult.current&&
calculateResult.current.input=== inputNumber
){
// If the input hasn't changed, reuse the cached result
return calculateResult.current.result;
}else{
// Calculate the result and store it in the ref
const result =calculateFib(inputNumber);
calculateResult.current={input: inputNumber, result };
In the snippet above, the useRef Hook, named calculateResult, is employed to optimize performance by caching the results of a computationally expensive calculation like the Fibonacci sequence. The calculateResult.current property stores both the input number and the calculated result, allowing for comparison on subsequent renders.
The useMemo Hook is used to memoize the calculation. It checks if the input number (inputNumber) has changed since the last render. If not, it returns the cached result from calculateResult.current, avoiding redundant computation. If the input number changes, the Fibonacci calculation is performed, and the result is stored in calculateResult.current for future reuse.
This memoization strategy improves the component's performance by preventing recalculations whenever the component re-renders due to unrelated state changes. While useRef offers performance benefits, knowing its potential drawbacks is essential.
Manual management: Unlike state variables managed with useState or useReducer, changes to the .current property of a ref attribute do not automatically trigger re-renders of your component. This means you need to manage updates and trigger re-renders manually when necessary and can add extra complexity to your code.
Potential memory leaks: If you're not careful, you can create dangling refs. This happens when a ref is still holding onto a reference to a DOM element or other object that has already been unmounted or removed from the DOM, leading to memory leaks.
Overuse: While refs are helpful in certain scenarios, overusing them can lead to a more complex and less maintainable codebase.
Debugging challenges: Since changes to refs don't trigger re-renders, debugging issues related to refs can sometimes be more complicated than debugging state-related problems.
Not suitable for array or object updates: Although you can store arrays or objects in a ref, updating individual properties or elements within them won't trigger re-renders. You'll need to manually update the entire array or object and trigger a re-render if you want those changes to be reflected in the UI. This can require more work than using state for mutable value structures.
To mitigate these drawbacks
Use the useRef when necessary and prioritize managing UI-related data with state (useState or useReducer) as it automatically triggers re-renders.
Always ensure proper cleanup of refs when components are removed from the DOM to prevent memory leaks.
Leverage debugging tools like React DevTools to track ref values and their impact if your code becomes overly reliant on refs.
Consider alternative approaches like lifting the state up or using context to streamline state management and component communication.
While both useRef and useState store values in React components, they serve different purposes and behave differently. Let's look at these Hooks, exploring their characteristics and how they contribute to state management in a React component.
Feature
useRef
useState
Mutable
Yes, the .current property can be changed directly
No, state updates must be done through the setter function (e.g., setCount)
Persistencea**crossr**enders
Yes, the value persists for the lifetime of the component
No, the value is reset on each re-render
Triggersr**e-render**
No, updating the .current property does not cause a re-render
Yes, updating state using the setter function triggers a re-render of the component
Commonu**sec**ases
Accessing DOM elements, storing previous values, managing timers/intervals, storing references
Managing UI state, storing data that directly affects the component's rendering
Before the Hooks era, React used createRef() for refs in their application. Let's break down their key distinctions when it comes to managing refs in React applications:
Feature
useRef Hook
createRef Function
Componentt**ype**
Exclusively used in functional components (introduced in React 16.8)
Designed for class components (pre-Hooks era)
Initialv**alue**
Takes an optional initial value, assigned to ref.current (defaults to undefined)
No initial value, ref.current is initially null
Re-renders
Returns the same ref object on each re-render, maintaining its value
Creates a new ref object on every re-render, losing the previous value
Persistence
Value persists for the entire component lifecycle
Value is lost on re-renders unless explicitly stored in a class component's instance variable
Flexibility
More flexible in functional components due to its persistence
Less flexible, requires additional state management for persistence in class components
If you're using functional components with React Hooks, useRef is the way to go. But if you're working with legacy class components, createRef is your best option.
However, consider refactoring to functional components and the useRef Hook for a more modern and maintainable approach. Next, let's discuss the useRef Hook in data fetched from content management systems.
useRef Hook in dynamic content fetched from CMSs
The useRef Hook, although not inherently tied to Content Management Systems (CMS), plays a crucial role in enhancing user interactions with dynamically fetched content from platforms like Hygraph, a GraphQL-Native Headless Content Management, and Federation System.
By storing references to specific elements within the fetched data, such as images or content blocks, developers can implement features like lazy loading, smooth scrolling, or interactive components.
Furthermore, useRef is valuable in optimizing data fetching from CMSs by caching results, especially for complex queries or large datasets. This caching mechanism reduces the load on the CMS and improves the application's performance as it avoids redundant data fetching operations.
While often overlooked, the useRef Hook is a powerful asset in a React developer's toolkit. It excels in managing references, optimizing performance, and enabling seamless interactions with DOM elements.
Understanding its capabilities and appropriate use cases allows developers to create more efficient, maintainable, and interactive React applications. Whether you're building complex animations, managing timers, or integrating with headless CMS platforms like Hygraph to optimize content delivery, useRef proves its value repeatedly.
Ready to explore the power of Hygraph? Sign up for a free-forever developer account and experience the seamless integration of Hygraph with React and its powerful Hook like useRef.
Blog Author
Motunrayo Moronfolu
Technical writer
Motunrayo Moronfolu is a Senior Frontend Engineer and Technical writer passionate about building and writing about great user experiences.
Share with others
Sign up for our newsletter!
Be the first to know about releases and industry news and insights.