React Useref
Topic | Source |
---|---|
React | React 16: The Complete Course (incl. React Router 4 & Redux) - Udemy |
useRef
is a React Hook that provides a way to create mutable references to elements or values that persist across renders without causing re-renders when they change.
useRef is commonly used for accessing and manipulating DOM elements, managing values that don't trigger re-renders, and interacting with imperative code or libraries.
You can create a ref using the useRef
function, like this:
const myRef = useRef(initialValue);
The myRef
object returned by useRef
has a current
property that can be used to store and access mutable values.
Unlike state variables or props, the value stored in a useRef
object does not trigger component re-renders when it changes. This makes it suitable for storing values that you want to persist between renders without affecting the component's rendering.
One common use case for useRef
is to access and interact with DOM elements. You can attach a ref
attribute to a JSX element and then access that element using the current
property of the useRef
object.
const myRef = useRef(null);
return <div ref={myRef}>This is a DOM element</div>;
// Access the DOM
const element = myRef.current;
ย ```
### Managing Previous Values
`useRef` is often used to store and access the previous value of a state or prop without causing re-renders. You can update the `current` property of the ref during each render to store the current value.
```jsx
const prevValueRef = useRef();
useEffect(() => {
prevValueRef.current = value;
}, [value]);
Common Use Cases
- Storing and accessing DOM elements.
- Managing values that need to persist between renders without causing re-renders.
- Storing and accessing previous values for comparison in
useEffect
or event handlers. - Interacting with imperative code and libraries.