Senior
How to store a value in a component without triggering a re-render?
sobes.tech AI
Answer from AI
In React, to store a value in a component without triggering a re-render, you can use the useRef hook. The value stored in useRef persists between renders, but changing this value does not cause the component to re-render.
Example:
import React, { useRef } from 'react';
function MyComponent() {
const countRef = useRef(0);
const increment = () => {
countRef.current += 1;
console.log('Current value:', countRef.current);
// The component will not re-render
};
return <button onClick={increment}>Increase</button>;
}
Thus, useRef is suitable for storing any data that does not affect the UI and does not require a re-render when changed.