Movatterモバイル変換


[0]ホーム

URL:


Is this page useful?

Validates correct usage of refs, not reading/writing during render. See the “pitfalls” section inuseRef() usage.

Rule Details

Refs hold values that aren’t used for rendering. Unlike state, changing a ref doesn’t trigger a re-render. Reading or writingref.current during render breaks React’s expectations. Refs might not be initialized when you try to read them, and their values can be stale or inconsistent.

How It Detects Refs

The lint only applies these rules to values it knows are refs. A value is inferred as a ref when the compiler sees any of the following patterns:

  • Returned fromuseRef() orReact.createRef().

    constscrollRef =useRef(null);
  • An identifier namedref or ending inRef that reads from or writes to.current.

    buttonRef.current =node;
  • Passed through a JSXref prop (for example<div ref={someRef} />).

    <inputref={inputRef}/>

Once something is marked as a ref, that inference follows the value through assignments, destructuring, or helper calls. This lets the lint surface violations even whenref.current is accessed inside another function that received the ref as an argument.

Common Violations

  • Readingref.current during render
  • Updatingrefs during render
  • Usingrefs for values that should be state

Invalid

Examples of incorrect code for this rule:

// ❌ Reading ref during render
functionComponent(){
constref =useRef(0);
constvalue =ref.current;// Don't read during render
return<div>{value}</div>;
}

// ❌ Modifying ref during render
functionComponent({value}){
constref =useRef(null);
ref.current =value;// Don't modify during render
return<div/>;
}

Valid

Examples of correct code for this rule:

// ✅ Read ref in effects/handlers
functionComponent(){
constref =useRef(null);

useEffect(()=>{
if(ref.current){
console.log(ref.current.offsetWidth);// OK in effect
}
});

return<divref={ref}/>;
}

// ✅ Use state for UI values
functionComponent(){
const[count,setCount] =useState(0);

return(
<buttononClick={()=>setCount(count +1)}>
{count}
</button>
);
}

// ✅ Lazy initialization of ref value
functionComponent(){
constref =useRef(null);

// Initialize only once on first use
if(ref.current ===null){
ref.current =expensiveComputation();// OK - lazy initialization
}

consthandleClick =()=>{
console.log(ref.current);// Use the initialized value
};

return<buttononClick={handleClick}>Click</button>;
}

Troubleshooting

The lint flagged my plain object with.current

The name heuristic intentionally treatsref.current andfooRef.current as real refs. If you’re modeling a custom container object, pick a different name (for example,box) or move the mutable value into state. Renaming avoids the lint because the compiler stops inferring it as a ref.



[8]ページ先頭

©2009-2025 Movatter.jp