React JS Tip: Avoid Using ref.current in the Render Body
It’s a common mistake even seasoned devs make.
function MyComponent() {
const divRef = useRef(null);
// ❗ Accessing ref.current during render
const width = divRef.current?.offsetWidth; // 🚫 Will be null on first render
return <div ref={divRef}>Width: {width}</div>;
}
Issue: ref.current is null during the first render because the DOM hasn’t mounted yet.
✅ Correct:
function MyComponent() {
const divRef = useRef(null);
const [width, setWidth] = useState(0);
useEffect(() => {
if (divRef.current) {
setWidth(divRef.current.offsetWidth);
}
}, []);
return <div ref={divRef}>Width: {width}</div>;
}
✅ useEffect runs after the component mounts, so the ref is ready to use.
🧠 Rule of thumb: Use ref.current only in effects or event handlers, not directly in render.
#ReactJS #FrontendTips #JavaScript #WebDev #ReactHooks