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
React DOM Resetting: Use useEffect and useRef for Safe Access
More Relevant Posts
-
🚀 Day 36 — #React_Refs Today I learned about React Refs 🔗 Ref means reference. Since React is a frontend library, sometimes we need to directly interact with the DOM elements. Refs provide a way to access DOM nodes or React elements created in the render method. 🧠 Why Refs are Useful 🔹 Managing focus 🔹 Text selection 🔹 Media playback 🔹 Triggering animations 🔹 Integrating third-party DOM libraries ✅ Important Notes 🔹 Refs directly interact with the DOM 🔹 They work imperatively, not declaratively 🔹 They bypass normal React state updates 🔹 Overusing refs is not recommended because it may affect performance 💡 Refs are powerful for special DOM-related tasks where state-based rendering is not enough. 🔥 Another important step toward mastering advanced React concepts. #React #ReactRefs #FrontendDevelopment #JavaScript #WebDevelopment #10000 Coders
To view or add a comment, sign in
-
-
🚨 Most developers misunderstand React re-rendering I used to think: 👉 “React re-renders = DOM updates” ❌ Wrong. Here’s what actually happens: 🧠 Rendering = React running your component 🔁 Re-render = React running it again BUT… 👉 React does NOT update the DOM every time Instead: ⚡ It creates a Virtual DOM ⚡ Compares old vs new (Reconciliation) ⚡ Updates ONLY what changed 💥 Real insight: 👉 The real problem is NOT DOM updates 👉 It’s unnecessary re-renders Example: Parent re-renders → Child also re-renders Even when nothing changed ❌ 🛠️ Fix: 🛡️ React.memo → skip child render if props same 📦 useMemo → keep props stable Together: 👉 Stable props + memoized component = no wasted work 🧠 Biggest learning today: 👉 “React doesn’t repaint everything… it only fixes what changed.” #React #Frontend #WebDevelopment #Performance #JavaScript #OpenSource
To view or add a comment, sign in
-
Mastering useState: The Most Important Hook in React If you're working with React, useState is one of the first hooks you learn — and also one you’ll use in almost every component you build. Yet many developers still use it incorrectly and run into stale state or unnecessary re-renders. useState allows you to add state to functional components. It returns an array with two values: the current state and a setter function. const [count, setCount] = useState(0); The real power (and common pitfall) comes when your new state depends on the previous state. Correct way: Using the functional updater (prev) => guarantees you always get the latest state, even when multiple updates happen quickly. A few best practices I always follow: Never mutate state directly. Always create a new object/array using the spread operator (...prev). Use computed property names [dynamicKey] when your key comes from a variable. Keep state as simple as possible. If your state object gets too complex, consider useReducer. I’ve seen many bugs disappear simply by switching from setState(newValue) to the functional form when the update relies on previous values. Whether you’re building a small UI or a complex audio/video player like the one I was recently working on, mastering useState patterns makes your code more predictable, cleaner, and easier to debug. What’s one useState trick or gotcha you’ve learned? Drop it in the comments #React #JavaScript #WebDevelopment #Frontend #CodingTips
To view or add a comment, sign in
-
-
Building My Own Reusable Star Rating Component in React As part of my journey learning React, I decided to stop relying on external npm packages for simple UI features (For security and Reliability reasons) and instead build them from scratch. One of the components I built recently is a fully reusable Star Rating component Features I implemented: - Configurable number of stars (max) - Controlled and uncontrolled rating support - Click interaction to set rating - Custom colors support (border, fill, shadow) - Reset / clear rating option - Callback function triggered when the user selects a rating, passing the updated rating value as an argument , this is helpfull for external handling (e.g: state sync with parent components) - Fully reusable design #React #JavaScript #FrontendDevelopment #WebDevelopment #LearningInPublic #Programming #UI #CleanCode
To view or add a comment, sign in
-
🚀 React.memo — Prevent Unnecessary Re-renders Like a Pro In React, re-renders are normal… 👉 But unnecessary re-renders = performance issues That’s where React.memo helps. 💡 What is React.memo? React.memo is a higher-order component (HOC) 👉 It memoizes a component 👉 Prevents re-render if props haven’t changed ⚙️ Basic Example const Child = React.memo(({ name }) => { console.log("Child rendered"); return <h1>{name}</h1>; }); 👉 Now it only re-renders when name changes 🧠 How it works 👉 React compares previous props vs new props If same: ✅ Skips re-render If changed: 🔁 Re-renders component 🔥 The Real Problem Without memo: <Child name="Priyank" /> 👉 Even if parent re-renders 👉 Child also re-renders ❌ With React.memo: ✅ Child re-renders only when needed 🧩 Real-world use cases ✔ Large component trees ✔ Expensive UI rendering ✔ Lists with many items ✔ Components receiving stable props 🔥 Best Practices (Most developers miss this!) ✅ Use with stable props ✅ Combine with useCallback / useMemo ✅ Use in performance-critical components ❌ Don’t wrap every component blindly ⚠️ Common Mistake // ❌ Passing new function each render <Child onClick={() => console.log("Click")} /> 👉 Breaks memoization → causes re-render 💬 Pro Insight (Senior-Level Thinking) 👉 React.memo is not magic 👉 It works only if: Props are stable Reference doesn’t change 📌 Save this post & follow for more deep frontend insights! 📅 Day 21/100 #ReactJS #FrontendDevelopment #JavaScript #PerformanceOptimization #ReactHooks #SoftwareEngineering #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
Unpopular opinion: If you're manually manipulating the DOM in React, you're not writing React. I see this more than I should: document.getElementById('box').style.color = 'red'; It works. Until it doesn't. On the next render, React overwrites your change. Now you have a bug you can't explain. And a 2am debugging session you didn't plan for. Here's what React actually wants you to do: → Describe WHAT the UI should look like → Let React figure out HOW to get there → Use useEffect when you need to step outside the render cycle → Use useRef when you genuinely need a DOM reference The moment you bypass React's virtual DOM, you're fighting the framework. And the framework always wins. useEffect isn't just a hook. It's React saying: "Trust me. I'll handle it after the render." Stop poking the DOM. Start thinking in React. #React #JavaScript #FrontendDevelopment #WebDev #SoftwareEngineering #Programming #ReactJS #DeveloperLife #CodeQuality #BuildInPublic #sde #SDE #DSA
To view or add a comment, sign in
-
🚀 Breaking Down a Basic React Component – Super Simple! 🧩 Ever wondered how React components actually work? This diagram makes it crystal clear, like digital Lego blocks you snap together for your UI. Key Parts Explained • Import React: Grabs the React library to make magic happen. 📥 • Function with Props: Takes inputs (like "greeting") and returns JSX – think data in, UI out! ⚡ • JSX Markup: Writes HTML-like code inside JS for dynamic content. ✨ • Export Default: Shares your component so other files can use it anywhere. 🔄 Components are reusable building blocks – master this anatomy, and building apps gets way easier! 💪 Who's building their first React project? Share below! 👇 #ReactJS #React #WebDevelopment #Frontend #FrontendDeveloper #LearnReact #JavaScript #JS #CodingTips #DeveloperLife #TechBeginners #BuildWithReact #Programming #CodeNewbie #WebDev #ReactHooks #NextJS #FullStack #DevCommunity #SoftwareEngineering #100DaysOfCode #LearnToCode #TechTips
To view or add a comment, sign in
-
-
If your React component has isLoading, isError, isEmpty and isSuccess as separate props, you have a problem. I have written this exact code. More than once. It starts small. You add isLoading to show a spinner. Then isError for the error state. Then isEmpty because the empty state needs its own UI. Then isSuccess for the confirmation screen. Now you have four boolean props. And they fight each other. What happens when isLoading and isError are both true? Which one wins? Nobody knows. The component does not know either. You just hope the parent passes the right combination. This is Boolean Prop Hell. And it is sitting in most React codebases right now. Booleans feel simple but they hide impossible states. 4 boolean props = 16 possible combinations. Your component can only handle maybe 4 of them. The other 12 are bugs waiting to happen. Replace all of them with a single status prop. One value. One source of truth. No impossible combinations. The component always knows exactly what to render. This is how every serious component library handles it. There is a reason for that. When you find yourself adding another boolean prop, stop for a second. Ask: is this a new state or just a variation of an existing one? Most of the time you do not need a new prop. You need a better status model. Before and after in the screenshot below 👇 #ReactJS #Frontend #WebDev #JavaScript
To view or add a comment, sign in
-
-
most React developers have too many useEffects. i did too. until i read this rule and couldn't unsee it: if you're using useEffect to sync state with another state you don't need useEffect. here's what i mean. (the pattern 1 .. i see everywhere) but pattern 2 give same result . no effect. no extra render cycle. useEffect is for syncing React with something outside React. - fetching data from an API - setting up a subscription - manually touching the DOM not for calculating values you could just... calculate. every unnecessary useEffect is a hidden render cycle your users pay for. before you write useEffect ask one question: am i syncing with something outside React, or am i just doing math? if it's math delete the effect. #reactjs #typescript #webdevelopment #buildinpublic #javascript
To view or add a comment, sign in
-
-
Topic: React Batching – Why Multiple setState Calls Don’t Always Re-render ⚡ React Batching – Multiple setState Calls, One Render (But Not Always) Ever written this and expected 2 re-renders? 👇 setCount(c => c + 1); setCount(c => c + 1); But React only re-renders once 🤯 Why? 👉 Batching 🔹 What is Batching? React groups multiple state updates and processes them in a single render cycle. 🔹 Why It Matters ✔ Better performance ✔ Fewer unnecessary renders ✔ Smoother UI updates 🔹 Before React 18 😓 Batching worked only in: 👉 Event handlers Not in: ❌ setTimeout ❌ Promises 🔹 After React 18+ 🚀 Automatic batching works almost everywhere: ✔ setTimeout ✔ async/await ✔ API calls 🔹 Example setTimeout(() => { setA(1); setB(2); }); 👉 Still only one render in modern React 💡 Important Note If you need immediate update: flushSync(() => setCount(1)); 📌 Golden Rule React tries to do more work in fewer renders. 💬 Did batching ever confuse you while debugging state updates? #React #ReactJS #StateManagement #FrontendDevelopment #JavaScript #WebDevelopment #DeveloperLife
To view or add a comment, sign in
More from this author
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development