You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
exportfunctionMyComponent(){constmyRef=useRef(null);// Initialized to `null`consthandleClick=()=>{// Updating the ref's value (e.g., to a DOM element)myRef.current=document.getElementById("my-element");// ❌ INCORRECT: `myRef` is always truthy (it's an object)if(myRef){// This block will always execute, even if `myRef.current` is nullconsole.log("Ref exists (but current might still be null!)");}};return<buttononClick={handleClick}>Click me</button>;}
exportfunctionMyComponent(){constmyRef=useRef(null);consthandleClick=()=>{myRef.current=document.getElementById("my-element");// ✅ CORRECT: Checks `myRef.current`, which may be truthy or falsyif(myRef.current){// This block won't execute, when `myRef.current` is nullconsole.log("Element found:",myRef.current);}};return<buttononClick={handleClick}>Click me</button>;}
The incorrect check (if (myRef)) always evaluates to true (since ref is an object), even when myRef.current is null or false.
This mistake is common when working with DOM refs or storing boolean flags in refs.
Unlike unused variables, this directly impacts runtime behavior silently.
This kind of seems like something TS should be warning you about - since without type info, an eslint rule can't know that useRef always returns a truthy object.
React Documentation: https://react.dev/reference/react/useRef
WRONG example:
The user should get warned that he is calling useRef improperly in that situation, instead it should be:
RIGHT example:
I think this is an easy mistake to make, one more important and likely than, for example, "no-unused-vars." And one very easy to lint.
The text was updated successfully, but these errors were encountered: