Introduction to useRef in React
useRef is a React Hook that allows you to create a mutable object which persists for the lifetime of a component. It’s often used for accessing DOM elements directly, storing mutable values like instance variables, and more.
Basic Syntax
To use useRef, you first need to import it from React:
import React, { useRef } from 'react';
Then you can initialize a ref in your component:
function MyComponent() {
const myRef = useRef(null);
return (
<div ref={myRef}>
Hello, World!
</div>
);
}
Common Use Cases
- Accessing DOM Elements
useRefis commonly used to access and interact with DOM elements
import React, { useRef } from 'react';
function FocusInput() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
2. Storing Mutable Values You can also use useRef to keep a mutable value that doesn’t trigger a re-render when changed.
import React, { useRef, useState } from 'react';
function Timer() {
const [count, setCount] = useState(0);
const countRef = useRef(count);
const incrementCount = () => {
countRef.current = countRef.current + 1;
setCount(countRef.current);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={incrementCount}>Increment</button>
</div>
);
}
3. Keeping Track of Previous Values Sometimes you need to track the previous value of a state or prop.
import React, { useState, useEffect, useRef } 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>
);
}
Key Points
- Mutable Object:
useRefreturns a mutable object,{ current: value }, wherecurrentcan be modified without causing a re-render. - Persistence: The value of
useRefpersists across re-renders. - No Re-render: Updating a ref does not trigger a component re-render, making it different from state.
- Initial Value: You can initialize the ref with an initial value, which can be
nullor any other value.
Best Practices
- Avoid Overuse: While
useRefis powerful, overusing it can lead to code that’s hard to understand and debug. Prefer state for values that affect rendering. - Read vs. Write: Use refs primarily for reading values and use state for values that need to trigger re-renders when changed.
- Callback Refs: For more complex scenarios, consider using callback refs, which offer more control over ref assignment and updates.
Conclusion
useRef is a versatile hook in React that provides a way to persist values across renders without causing re-renders. It’s particularly useful for accessing DOM elements, storing mutable values, and keeping track of previous values. By understanding and applying useRef correctly, you can enhance your React applications with more powerful and efficient interactions.
