MENU
Functional Initialization
Like useState, if you call a function to 'lazily' set the initial value of useRef, the function will be called on every render.
RESETRUNFULL
RESETRUNFULL
function MyButton() {
const [x,setX] = React.useState(0);
const f = x=>{console.log('firing!'); return x;}
const inputEl = React.useRef(f(null)); // f() called on every render even if ref not used
return (<button onClick={()=>setX(x+1)}>Render</button>);}ReactDOM.render(<MyButton/>,document.querySelector("div"));
useRef does not accept a special function overload like useState. Instead, you can write your own function that creates and sets it lazily:
RESETRUNFULL
RESETRUNFULL
function Image(props) {
const ref = useRef(null); // ✅ IntersectionObserver is created lazily once
function getObserver() {
if (ref.current === null) {
ref.current = new IntersectionObserver(onIntersect);
}
return ref.current;
} // When you need it, call getObserver() // ...}