Table of contents
Refs are a way to store a reference to a React component or DOM element. The useRef
hook is used for creating mutable references to elements or values that persist across renders.
Creating a Ref
To create a ref, we use the useRef
hook in a functional component. Here's an example:
import { useRef } from 'react';
function TextInput() {
const inputRef = useRef(null);
function focusInput() {
inputRef.current.focus();
}
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
In this example, we create a inputRef
ref by calling useRef
with an initial value of null
. We then use this ref to set the ref
prop of an input
element. We also create a focusInput
function that calls the focus
method on the inputRef.current
element when a button is clicked.
Storing Mutable Values
In addition to storing references to elements, refs can also be used to store mutable values that persist across renders. Here's an example:
import { useState, useRef } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const prevCountRef = useRef(0);
function handleIncrement() {
prevCountRef.current = count;
setCount(count + 1);
}
return (
<div>
<p>Current Count: {count}</p>
<p>Previous Count: {prevCountRef.current}</p>
<button onClick={handleIncrement}>Increment Count</button>
</div>
);
}
In this example, we create a prevCountRef
ref to store the previous value of the count
state. We use the handleIncrement
function to update both the count
state and the prevCountRef.current
value.
Conclusion
The useRef
hook is used for creating mutable references to elements or values that persist across renders. By calling useRef
with an initial value of null
or any other value, we can create a ref to a React component or DOM element. We can also use refs to store mutable values that persist across renders, allowing us to access previous state or values.
The next article in this series will cover the Memoization hooks, useMemo
and useCallback
. These hooks are used to optimize performance by memoizing expensive computations or preventing unnecessary re-renders in React components.