The Power of the useRef Hook in React
React's hook system has undoubtedly revolutionized the way we write React components. From state management with useState
to effect handling with useEffect
, hooks have made our React code more concise and readable. One of the more versatile hooks in the React arsenal is the useRef
hook. In this blog post, we'll deep dive into the useRef
hook and explore its uses, supported with practical code examples.
What is useRef
?
The useRef
hook is typically used to access the DOM directly, but it can do more than just that. Essentially, useRef
returns a mutable ref object with a current
property. This object persists for the entire lifetime of the component, making it great for preserving values without causing a re-render.
Use Cases for useRef
Directly Accessing DOM Elements: This is the most common use case for
useRef
.Let's take a look at an example where we want to focus on an input field as soon as our component mounts:
import React, { useEffect, useRef } from 'react'; function AutoFocusInput() { const inputRef = useRef(null); useEffect(() => { inputRef.current.focus(); }, []); return <input ref={inputRef} />; }
Here, the input element is associated with the ref object using the
ref
prop. We then utilizeuseEffect
to focus on this input when the component mounts.Preserving Values Without Causing Re-renders:
In class components, developers often use instance variables to store values that shouldn't trigger a re-render. In functional components,
useRef
can serve a similar purpose. The values it holds don't cause a component to re-render, making it a good fit for preserving values that you don't want to put in the state.Let’s assume you want to track how many times a user clicks a button, but you don't want to re-render the component every time the count changes:
import React, { useRef } from 'react'; function ClickCounter() { const count = useRef(0); const handleClick = () => { count.current += 1; console.log(`Button clicked ${count.current} times`); }; return <button onClick={handleClick}>Click Me</button>; }
Storing Previous State or Props:
Sometimes, we may need to compare the previous and current values of props or state.
useRef
can come in handy in such scenarios:import React, { useState, useEffect, useRef } from 'react'; function DisplayPrevValue() { const [value, setValue] = useState(''); const prevValue = useRef(); useEffect(() => { prevValue.current = value; }, [value]); return ( <div> <input value={value} onChange={e => setValue(e.target.value)} /> <p>Current Value: {value}</p> <p>Previous Value: {prevValue.current}</p> </div> ); }
- In the code above, we store the previous value in
prevValue
usinguseRef
. WithuseEffect
, we update theprevValue
whenever ourvalue
changes.
- In the code above, we store the previous value in
Conclusion
The useRef
hook in React is a powerful tool, often associated with DOM manipulation. However, as we've seen, its capabilities go beyond just the DOM. Whether you're preserving values without triggering re-renders or tracking previous prop and state values, useRef
has got you covered.
Remember, while useRef
provides us with direct access and manipulation capabilities, it's essential to use it judiciously. Overuse or misuse can lead to unexpected behavior in your applications.
Subscribe to my newsletter
Read articles from Shariq Ansari directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by