#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:

  1. Persistence Across Renders:
    • useRef returns an object with a .current property that persists for the full lifetime of the component.
  2. Mutation Without Re-rendering:
    • Changes to the .current value don't trigger component re-renders, unlike state updates.
  3. DOM References:
    • Commonly used to reference and interact with DOM elements directly.

Why It Matters:


How to Implement:

  1. Initialize the Ref:
    • const myRef = useRef(initialValue);
  2. Access or Update the Value:
    • Access via myRef.current
    • Update via myRef.current = newValue;
  3. Reference DOM Elements:
    • Assign to JSX elements: <div ref={myRef}></div>

Example:

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}
;
}
```

Connections:


References:

  1. Primary Source:
    • React Documentation, Hooks API Reference
  2. Additional Resources:

Tags:

#React #Hooks #useRef #DOM #Optimization #PersistentValues


Connections:


Sources: