#atom
useRef - Persistent Values Without Re-renders in React
Core Idea:
The useRef hook creates a mutable reference that persists across renders without triggering re-renders when its value changes, making it ideal for storing values that need to survive re-renders without affecting the component's rendering cycle.
Key Principles:
- Persistence Across Renders:
- useRef returns an object with a .current property that persists for the full lifetime of the component.
- Mutation Without Re-rendering:
- Changes to the .current value don't trigger component re-renders, unlike state updates.
- DOM References:
- Commonly used to reference and interact with DOM elements directly.
Why It Matters:
- Performance Optimization:
- Allows storing values without causing unnecessary re-renders.
- DOM Manipulation:
- Provides a way to access and modify DOM elements imperatively.
- Previous Values Tracking:
- Enables comparison between current and previous renders' values.
How to Implement:
- Initialize the Ref:
const myRef = useRef(initialValue);
- Access or Update the Value:
- Access via
myRef.current - Update via
myRef.current = newValue;
- Access via
- Reference DOM Elements:
- Assign to JSX elements:
<div ref={myRef}></div>
- Assign to JSX elements:
Example:
-
Scenario:
- A component needs to track the previous value of a prop for comparison.
-
Application:
function Component({value}) {
const prevValueRef = useRef();
useEffect(() => {
// Store current value for next render
prevValueRef.current = value;
}, [value]);
const prevValue = prevValueRef.current;
return
Previous: {prevValue}, Current: {value}
;}
```
- Result:
- The component can compare current and previous values without extra re-renders.
Connections:
- Related React Concepts:
- useState: For values that should trigger re-renders.
- useEffect: Often used together to perform side effects with refs.
- Broader Programming Concepts:
- Mutable References: Controlled mutation in otherwise immutable patterns.
- Imperative Programming: Direct manipulation vs declarative updates.
References:
- Primary Source:
- React Documentation, Hooks API Reference
- Additional Resources:
Tags:
#React #Hooks #useRef #DOM #Optimization #PersistentValues
Connections:
Sources:
- From: AG Grid