React DOM Resetting: Use useEffect and useRef for Safe Access

Junior me: "Why is my React component randomly resetting?" Senior me: "Did you touch the DOM directly?" Junior me: "...maybe" Here's the lesson that took me longer than I'd like to admit: React owns the DOM. You don't. When you do this 👇 document.querySelector('.box').style.display = 'none'; React has no idea. On the next re-render, it overwrites you. Silently. Mercilessly. The right way? ✅ Use useEffect to run side effects after render ✅ Use useRef for safe, controlled DOM access ✅ Use state to drive UI changes — not DOM calls useEffect(() => {  inputRef.current.focus(); }, []); This is React-aware. It survives re-renders. It cleans up after itself. The mental shift that changes everything: You're not telling the DOM what to do. You're telling React what the UI should look like. React does the rest. Took me a while to get this. Hope it saves you some debugging hours. 🙌 #React #useEffect #JavaScript #FrontendDevelopment #WebDev #ReactJS #Programming #DeveloperLife #TechTips #CodeNewbie

To view or add a comment, sign in

Explore content categories