Education
Software Development Executive - I
Last updated onSep 29, 2023
Last updated onSep 15, 2023
In the world of React, hooks play a crucial role in managing state and side effects in functional components. Among these hooks, useRef stands out as a powerful tool for creating mutable reference objects. This blog post delves into the useRef hook, exploring its definition, purpose, and comparison with other React hooks.
We'll also discuss when and how to use useRef, its basic syntax, and provide examples of useRef for DOM manipulation and storing mutable variables. Whether you're a seasoned React developer or a beginner, this comprehensive guide will help you understand and effectively use the useRef hook in your React applications.
The useRef hook in React is a function that returns a mutable ref object. This ref object persists for the full lifetime of the component. The returned object's .current property is initialized with the passed argument (initialValue). This initial value can be anything, and it's the value that the mutable ref object will hold during the component's initial render.
1 import React, { useRef } from 'react'; 2 3 function App() { 4 const ref = useRef('initial value'); 5 6 return ( 7 <div> 8 <input ref={ref} type="text" /> 9 </div> 10 ); 11 } 12
In the above example, the useRef hook is used to create a reference to an input element in a functional component. The ref attribute is then assigned to the input element, allowing us to access the DOM element directly.
The useRef hook is commonly used for accessing DOM elements and storing mutable values. It's important to note that changing the ref object or the current property doesn't trigger re-rendering of the component.
The useRef hook is unique among React hooks. Unlike useState or useEffect, changes to a useRef don't trigger re-renders of the component. This makes useRef an excellent choice for storing values that you want to persist across re-renders but don't want to cause re-rendering.
1 import React, { useState, useRef } from 'react'; 2 3 function App() { 4 const [state, setState] = useState('initial value'); 5 const ref = useRef('initial value'); 6 7 const handleClick = () => { 8 setState('new value'); 9 ref.current = 'new value'; 10 }; 11 12 return ( 13 <div> 14 <button onClick={handleClick}>Change Values</button> 15 <p>State: {state}</p> 16 <p>Ref: {ref.current}</p> 17 </div> 18 ); 19 } 20
In the above code, both useState and useRef are initialized with the same initial value. When the button is clicked, both the state and the ref are updated. However, only the change in state causes the component to re-render.
The useRef hook is commonly used in a variety of scenarios in React development. Here are some of the most common use cases:
Accessing DOM Elements: useRef is often used to create a reference to a DOM element. This reference can then be used to read or modify the properties of that element.
1 import React, { useRef } from 'react'; 2 3 function App() { 4 const inputRef = useRef(); 5 6 const focusInput = () => { 7 inputRef.current.focus(); 8 }; 9 10 return ( 11 <div> 12 <input ref={inputRef} type="text" /> 13 <button onClick={focusInput}>Focus the input</button> 14 </div> 15 ); 16 } 17
In the above example, useRef is used to create a reference to an input field. When the button is clicked, the input field is focused.
Storing Mutable Values: useRef can also be used to store mutable values. The value stored in a ref persists across re-renders and does not cause a re-render when changed.
1 import React, { useRef, useEffect } from 'react'; 2 3 function App() { 4 const renderCount = useRef(0); 5 6 useEffect(() => { 7 renderCount.current = renderCount.current + 1; 8 }); 9 10 return ( 11 <div> 12 <p>This component has rendered {renderCount.current} times.</p> 13 </div> 14 ); 15 } 16
In this example, useRef is used to keep track of the number of times the component has been rendered. The value is incremented in a useEffect hook after each render.
While useRef is a powerful tool, it's not always the best solution. Here are a few scenarios where you should avoid using useRef:
Storing State: If you need to store a value that, when changed, should cause the component to re-render, you should use useState or useReducer instead of useRef.
Storing Immutable Values: If the value you're storing doesn't change over time, consider using a constant instead of a ref.
The useRef hook in React is a built-in hook that allows you to create mutable reference objects. The basic syntax of useRef is as follows:
1 import React, { useRef } from 'react'; 2 3 function App() { 4 const ref = useRef(initialValue); 5 } 6
In the above code, useRef is called with an initial value, and it returns a mutable ref object. This ref object is then stored in a variable (in this case, ref).
Let's break down the components of useRef:
Importing useRef: Before you can use useRef, you need to import it from 'react'. This is done using the import statement.
Calling useRef: useRef is a function, and you call it with an initial value. This initial value is what the ref will hold during the component's initial render.
The Ref Object: useRef returns a mutable ref object. This object has a single property, .current, which holds the current value of the ref. The .current property is initialized to the initial value passed to useRef.
1 import React, { useRef } from 'react'; 2 3 function App() { 4 const ref = useRef('initial value'); 5 6 console.log(ref.current); // 'initial value' 7 } 8
In the above example, useRef is called with the initial value 'initial value'. The returned ref object is then logged to the console, showing that the .current property is indeed 'initial value'.
A simple example of how to use the useRef hook in a functional component to store a mutable variable, specifically a timer ID for a setInterval function.
1 import React, { useRef, useEffect } from 'react'; 2 3 function Timer() { 4 const timerIdRef = useRef(); 5 6 useEffect(() => { 7 timerIdRef.current = setInterval(() => { 8 console.log('Timer tick'); 9 }, 1000); 10 11 return () => { 12 clearInterval(timerIdRef.current); 13 }; 14 }, []); 15 16 return ( 17 <div> 18 Check your console for timer ticks every second. 19 </div> 20 ); 21 } 22
Here's a step-by-step walkthrough of the code:
In this example, useRef is used to create a reference to a mutable variable, the timer ID. This reference is stored in timerIdRef. The useEffect hook sets up an interval when the component mounts and stores the ID of the interval in timerIdRef.current. When the component unmounts, the cleanup function of the useEffect hook uses the ID stored in timerIdRef.current to clear the interval.
The useRef hook in React is a powerful tool that allows you to create a reference to a DOM element. This reference can be used to read or modify properties of the DOM element, effectively allowing you to manipulate the DOM directly from your React code.
While React promotes a declarative approach to building UIs, there are times when you might need to imperatively manipulate the DOM. For example, you might need to set the focus on an input field, measure the dimensions of an element, or interact with a third-party library that manipulates the DOM directly.
In these cases, useRef can be used to create a reference to a DOM element. This reference is an object with a current property that points to the current instance of the DOM element. You can then use this reference to manipulate the DOM element.
In this example, we'll create a functional component with a div element and a button. When the button is clicked, the color of the div element will be toggled between red and blue.
1 import React, { useRef } from 'react'; 2 3 function ColorToggle() { 4 const divRef = useRef(); 5 6 const toggleColor = () => { 7 const currentColor = divRef.current.style.backgroundColor; 8 divRef.current.style.backgroundColor = currentColor === 'red' ? 'blue' : 'red'; 9 }; 10 11 return ( 12 <div> 13 <div ref={divRef} style={{backgroundColor: 'red', height: '100px', width: '100px'}}></div> 14 <button onClick={toggleColor}>Toggle color</button> 15 </div> 16 ); 17 } 18
In this example, useRef is used to create a reference to the div element. This reference is stored in divRef. The toggleColor function is an event handler that gets triggered when the button is clicked. Inside this function, divRef.current refers to the div element in the DOM. The color of the div element is toggled between red and blue by changing the backgroundColor property of divRef.current.style.
In addition to accessing DOM elements, useRef can also be used to store mutable variables. This is useful when you need to keep track of a value that can change over time and doesn't cause a re-render when it changes.
The value stored in a ref persists across re-renders, making it an ideal place to store values that you want to persist across the lifetime of the component but don't want to cause a re-render when they change.
In this example, we'll create a functional component that keeps track of the number of times a button is clicked without causing a re-render.
1 import React, { useRef } from 'react'; 2 3 function ClickCounter() { 4 const clickCountRef = useRef(0); 5 6 const incrementClickCount = () => { 7 clickCountRef.current = clickCountRef.current + 1; 8 alert(`Button clicked ${clickCountRef.current} times.`); 9 }; 10 11 return ( 12 <div> 13 <button onClick={incrementClickCount}>Click me</button> 14 </div> 15 ); 16 } 17
In this example, useRef is used to create a ref that holds the number of times the button has been clicked. This ref is stored in clickCountRef. The incrementClickCount function is an event handler that gets triggered when the button is clicked. Inside this function, the current property of clickCountRef is incremented, and an alert is displayed with the current click count.
This example demonstrates how useRef can be used to store mutable variables that persist across re-renders without causing a re-render when they change.
In this blog post, we've explored the useRef hook in React, a powerful tool that allows you to create mutable reference objects. We've learned that useRef is commonly used for accessing DOM elements and storing mutable variables that persist across re-renders without causing a re-render when they change.
While useRef is a versatile tool, it's important to remember that it's not always the best solution. React is primarily a declarative framework, and most of the time, you should not need to use refs. However, when you do need to bridge the gap between the declarative React world and the imperative DOM world, or when you need to store mutable values that persist across re-renders, useRef is an invaluable tool in your React toolkit.
We hope this blog post has provided you with a solid understanding of useRef and how to use it effectively in your React applications.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.