useRef
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.
It's more commonly used to store references to DOM elements, but I've also seen used as a sort of memo for accessing large JSON maps
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 <div>Previous: {prevValue}, Current: {value}</div>;
}
- Result:
- The component can compare current and previous values without extra re-renders.
Connections:
- Related React Concepts:
- Broader Programming Concepts:
- Mutable References: Controlled mutation in otherwise immutable patterns.
- Imperative Programming: Direct manipulation vs declarative updates.