Stop disabling the exhaustive-deps linter in your React Effects ⚛️. we all did the same dirty hack: // eslint-disable-next-line 👇. It is the most common frustrating scenario in React development: You write a useEffect to connect to a websocket or track an analytics event. Inside that effect, you need to read the current value of a state variable—like a shopping cart count or a UI theme. But the moment you read that state, the React linter screams at you to add it to the dependency array. If you add it, your effect re-runs every time the state changes (destroying your websocket connection!). If you don't add it, your build fails. So, we all did the same dirty hack: // eslint-disable-next-line. React finally solves this permanently with useEffectEvent. ❌ The Legacy Way (eslint-disable): Forces you to break the rules of React. Creates a massive risk for stale closures and hidden bugs. Makes your code harder to maintain and review. ✅ The Modern Way (useEffectEvent): Extracts your "event" logic cleanly out of your "lifecycle" logic! • Always Fresh: It guarantees your callback will always read the absolute latest props and state. • Non-Reactive: It is intentionally ignored by the dependency array. It will never cause your useEffect to re-run. • Clean Code: You can finally turn your linter rules back on and trust your dependencies again. The Shift: We are moving away from fighting the framework and using dedicated primitives to separate reactive synchronization from non-reactive events. #ReactJS #React19 #WebDevelopment #Frontend #JavaScript #CleanCode #SoftwareEngineering #TechTips #WebDev #WebPerf #Tips #DevTips #ReactTips #FrontendDeveloper #DeveloperTips
React useEffectEvent solves eslint-disable hacks
More Relevant Posts
-
React keeps evolving but one thing hasn’t changed: Clean, maintainable components still matter more than trendy patterns. There’s so much noise around tools, libraries and “must-know” tricks that it’s easy to overlook simple patterns that make day to day code better. So switching gears a little from my usual reflective posts today I wanted to share something practical from my experience, 5 React patterns I keep coming back to in real projects that help reduce component bloat, improve readability, and keep code easier to scale. Inside the carousel: 1. Early returns over nested conditions 2. Custom hooks for cleaner logic 3. Object maps over condition chains 4. When not to overuse useMemo 5. Splitting UI from business logic None of these are flashy. They’re just small patterns that compound. Save it for your next React refactor if useful. ⚛️♻️ #ReactJS #FrontendDevelopment #JavaScript #SoftwareEngineering #WebDevelopment #CleanCode #FullStackDeveloper
To view or add a comment, sign in
-
𝐈𝐬 𝐲𝐨𝐮𝐫 `useEffect` 𝐡𝐨𝐨𝐤 𝐫𝐮𝐧𝐧𝐢𝐧𝐠 𝐭𝐨𝐨 𝐨𝐟𝐭𝐞𝐧, 𝐨𝐫 𝐧𝐨𝐭 𝐞𝐧𝐨𝐮𝐠𝐡? 𝐘𝐨𝐮'𝐫𝐞 𝐧𝐨𝐭 𝐚𝐥𝐨𝐧𝐞. I’ve seen countless `useEffect` bugs boil down to one thing: incorrect dependency arrays. It’s deceptively simple, but a missing dependency can lead to stale closures and unexpected behavior, while an unnecessary one can trigger re-renders like crazy. Consider this: if you define a function or object inside your component and use it in `useEffect`, it must be in your dependency array. However, if that function itself isn't memoized with `useCallback` (or the object with `useMemo`), it becomes a new reference on every render, causing your `useEffect` to fire relentlessly. The Fix: 1. Be explicit: List all values from your component scope that `useEffect` uses. ESLint usually flags this for a reason. 2. Memoize functions/objects: If a function or object needs to be a dependency but shouldn't trigger re-runs unless its own dependencies change, wrap it in `useCallback` or `useMemo`. ```javascript // Problem: myApiCall changes every render if not memoized const MyComponent = ({ id }) => { const myApiCall = () => fetch(`/data/${id}`); useEffect(() => { myApiCall(); // myApiCall is a new function on every render }, [myApiCall]); // Infinite loop! } // Solution: const MyComponent = ({ id }) => { const myApiCall = useCallback(() => fetch(`/data/${id}`), [id]); useEffect(() => { myApiCall(); }, [myApiCall]); // Now, myApiCall only changes when 'id' changes } ``` It's a subtle but critical distinction that keeps your React apps performant and predictable. What's the trickiest `useEffect` bug you've ever had to squash? #React #JavaScript #FrontendDevelopment #WebDev #Performance
To view or add a comment, sign in
-
use() is the first React hook you can call inside an if statement. Not a typo. React 19 quietly broke the "Rules of Hooks" - for exactly one hook. For years the rules were absolute: - Always call hooks in the same order - Never inside conditions, loops, or early returns use() ignores both. On purpose. What use() replaces: - useState + useEffect just to unwrap a promise - useContext pinned to the top of every render - Manual "if (!data) return <Spinner />" loading guards What use() actually does: - Unwraps a promise: const data = use(promise) - Reads context: const theme = use(ThemeContext) - Works inside if, for, ternaries, early returns - Suspends the component automatically while pending The mental model shift: Fetch the promise in the parent. use() it in the child. Wrap in <Suspense>. Done. If you're still writing useEffect(() => fetch().then(setData), []) in a React 19 codebase - React is now doing that work for you. Which React hook do you still reach for out of habit - even after React 19 made it obsolete? #React #React19 #Frontend #WebDev #JavaScript #LearnInPublic
To view or add a comment, sign in
-
-
🚀 Stop Managing State Manually — Let React Do the Heavy Lifting For a long time in React (especially React 17/18), handling form submissions meant writing extra logic: managing loading state, preventing default behavior, handling async calls manually… and repeating this pattern again and again. It worked — but it wasn’t elegant. Now with React 19, things are changing in a powerful way. ✨ With hooks like useActionState, React introduces a more declarative and streamlined approach: No more manual loading state management No need for repetitive event handling Cleaner and more readable components Built-in handling of async actions Instead of telling React how to handle everything step-by-step, we now focus on what we want — and let React take care of the rest. 👉 This shift is not just about writing less code. It’s about writing better code. Code that is: ✔ Easier to maintain ✔ Less error-prone ✔ More scalable ✔ More aligned with modern frontend architecture As developers, growth comes from unlearning old patterns and embracing better ones. 💡 The real question is: Are we just writing code that works… or are we writing code that evolves? #React19 #FrontendDevelopment #JavaScript #WebDevelopment #CleanCode #CodingJourney #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Crack the Code: The React Lifecycle (Core Level) Ever wondered how React actually manages the life of a component? Whether you’re prepping for a Senior Dev interview or just trying to squash that persistent memory leak, mastering the Lifecycle Phases is your secret weapon. 🛠️ React components are like living organisms: they are born, they grow, and they eventually pass away. 1️⃣ The Birth: Mounting Phase This is where it all begins. React initializes state and builds the initial Virtual DOM. The Hook: useEffect(() => { ... }, []) Pro Tip: Use this phase for initial API calls or setting up subscriptions. If you leave the dependency array empty, it runs exactly once—like a birth certificate! 2️⃣ The Growth: Updating Phase Whenever props or state change, React springs into action. This is where the magic of Diffing happens—React compares the old Virtual DOM with the new one to update only what’s necessary. The Hook: useEffect(() => { ... }, [dependency]) Pro Tip: Always be intentional with your dependency array. Missing a dependency can lead to stale data; adding too many can cause infinite loops! 🔄 3️⃣ The End: Unmounting Phase The most ignored phase, but arguably the most critical for performance. 🧹 The Hook: The Cleanup Function inside useEffect. Why it matters: If you don't clear your setInterval or unsubscribe from a socket here, you’re inviting memory leaks to crash your party. 💡 The "Core Level" Secret: Render vs. Commit To keep your apps buttery smooth, React splits work into two internal phases: Render Phase: Pure calculation. React figures out what changed. It can pause or restart this work if a higher-priority task comes in. Commit Phase: This is where React actually touches the Real DOM. It’s fast, synchronous, and happens in one go. 🧠 The Mental Model Shift In modern React, stop thinking about "methods" and start thinking about Synchronization. useEffect isn't just a lifecycle hook—it’s a tool to synchronize your component with an external system (the API, the DOM, or a Window event). Are you building for performance or just for functionality? Let's discuss in the comments! 👇 #ReactJS #WebDevelopment #FrontendEngineers #CodingTips #JavaScript #SoftwareArchitecture
To view or add a comment, sign in
-
-
You wrapped your component in React.memo… but it still re-renders 🤔 I ran into this more times than I’d like to admit. Everything looks correct. You’re using React.memo. Props don’t seem to change. But the component still re-renders on every parent update. Here’s a simple example: const List = React.memo(({ items }) => { console.log('List render'); return items.map(item => ( <div key={item.id}>{item.name}</div> )); }); function App() { const [count, setCount] = React.useState(0); const items = [{ id: 1, name: 'A' }]; return ( <> <button onClick={() => setCount(count + 1)}> Click </button> <List items={items} /> </> ); } When you click the button the List still re-renders. At first glance, it feels wrong. The data didn’t change… so why did React re-render? The reason is subtle but important: every render creates a new array. So even though the content is the same, the reference is different. [] !== [] And React.memo only does a shallow comparison. So from React’s perspective, the prop did change. One simple fix: const items = React.useMemo(() => [ { id: 1, name: 'A' } ], []); Now the reference stays stable and memoization actually works. Takeaway React.memo is not magic. It only helps if the props you pass are stable. If you create new objects or functions on every render, you’re effectively disabling it without realizing it. This is one of those bugs that doesn’t throw errors… but quietly hurts performance. Have you ever debugged something like this? 👀 #reactjs #javascript #frontend #webdevelopment #performance #reactperformance #softwareengineering #programming #coding #webdev #react #typescript
To view or add a comment, sign in
-
-
🔯 You can finally delete <Context.Provider> 👇 For years, the Context API introduced a small but persistent redundancy. We defined a Context object, yet we couldn't render it directly-we had to access the.Provider property every single time. 🔯 React 19 removes this requirement. ❌ The Old Way: UserContext.Provider It often felt like an implementation detail leaking into JSX. Forget Provider, and your app might silently fail or behave unexpectedly. ✅ The Modern Way: <UserContext> The Context object itself is now a valid React component. Just render it directly. Why this matters ❓ 📉 Less Noise - Cleaner JSX, especially with deeply nested providers 🧠 More Intuitive - Matches how we think: "wrap this in UserContext" 💡Note: Note: <Context.Consumer> is also largely dead in favor of the use hook or useContext. Starting in React 19, you can render <SomeContext> as a provider. In older versions of React, use <SomeContext.Provider>. 💬 Have you tried this in your project? 💬 React 18 or 19 — what are you using? 🔗 Learn More: React Context Docs: https://lnkd.in/dbVWdc-C #React #JavaScript #WebDevelopment #Frontend #React19 #ModernReact #ReactHook #CodingLife #DeveloperJourney #SoftwareDeveloper
To view or add a comment, sign in
-
-
🚀 5 React Mistakes I Made as a Beginner (And How to Fix Them) When I first started building with React, I made a lot of mistakes that slowed me down and introduced bugs I couldn't explain. Here are 5 of the most common ones — and how to fix them: ❌ #1 — Not cleaning up useEffect Forget to return a cleanup function? Hello, memory leaks. ✅ Always return a cleanup for timers, event listeners, and subscriptions. ❌ #2 — Using index as a key in lists This breaks React's reconciliation and causes weird UI bugs. ✅ Always use a unique ID from your data as the key prop. ❌ #3 — Calling setState directly inside render This creates an infinite re-render loop. ✅ Keep state updates inside event handlers or useEffect only. ❌ #4 — Fetching data without handling loading and error states Your UI breaks or shows nothing while data loads. ✅ Always manage three states: loading, error, and success. ❌ #5 — Putting everything in one giant component Hard to read, hard to debug, impossible to reuse. ✅ Break your UI into small, focused, reusable components. These mistakes cost me hours of debugging. I hope sharing them saves you that time. If you found this helpful, feel free to repost ♻️ — it might help another developer on their journey. 💬 Which of these mistakes have you made? Drop a comment below! #React #JavaScript #WebDevelopment #Frontend #MERNStack #ReactJS #100DaysOfCode #CodingTips #Developer
To view or add a comment, sign in
-
🚀 Controlled vs Uncontrolled Components in React — Real-World Perspective Most developers learn: 👉 Controlled = React state 👉 Uncontrolled = DOM refs But in real applications… 👉 The choice impacts performance, scalability, and maintainability. 💡 Quick Recap 🔹 Controlled Components: Managed by React state Re-render on every input change 🔹 Uncontrolled Components: Managed by the DOM Accessed via refs ⚙️ The Real Problem In large forms: ❌ Controlled inputs → Too many re-renders ❌ Uncontrolled inputs → Hard to validate & manage 👉 So which one should you use? 🧠 Real-world Decision Rule 👉 Use Controlled when: ✔ You need validation ✔ UI depends on input ✔ Dynamic form logic exists 👉 Use Uncontrolled when: ✔ Performance is critical ✔ Minimal validation needed ✔ Simple forms 🔥 Performance Insight Controlled input: <input value={name} onChange={(e) => setName(e.target.value)} /> 👉 Re-renders on every keystroke Uncontrolled input: <input ref={inputRef} /> 👉 No re-render → better performance ⚠️ Advanced Problem (Most devs miss this) 👉 Large forms with 20+ fields Controlled approach: ❌ Can slow down typing 👉 Solution: ✔ Hybrid approach ✔ Use libraries (React Hook Form) 🧩 Industry Pattern Modern apps often use: 👉 Controlled logic + Uncontrolled inputs internally Example: ✔ React Hook Form ✔ Formik (optimized patterns) 🔥 Best Practices ✅ Use controlled for logic-heavy forms ✅ Use uncontrolled for performance-critical inputs ✅ Consider form libraries for scalability ❌ Don’t blindly use controlled everywhere 💬 Pro Insight (Senior Thinking) 👉 This is not about “which is better” 👉 It’s about choosing the right tool for the problem 📌 Save this post & follow for more deep frontend insights! 📅 Day 17/100 #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #PerformanceOptimization #SoftwareEngineering #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
I made React slower trying to optimize it. Wrapped everything in useMemo. Added useCallback everywhere. Felt productive. Performance got worse. Here's what I didn't understand about re-renders 👇 4 things that trigger a re-render: > State change > Prop change > Parent re-renders (even if YOUR props didn't change) > Context update That third one is responsible of unnecessary re-renders I've seen in real codebases. The fix isn't memorizing APIs. It's this order: 1. Profile first Open React DevTools Profiler. Find the actual problem. Takes 2 minutes. 2. Wrap the right components in React.memo Not all of them. Only components that are expensive AND receive stable props. 3. Stabilise your functions with useCallback Without it - new function reference every render --> child always re-renders. Doesn't matter if you have React.memo. 4. useMemo for heavy calculations only Not for "this array map looks expensive." Only when Profiler proves it. The rule I follow now: Don't optimise what you haven't measured. One change in the right place beats 10 changes in the wrong ones. What's the most unnecessary useMemo you've ever written? 😄 #React #JavaScript #Frontend #WebDev
To view or add a comment, sign in
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
Wilson Guiraldelli Felipe Lima Marques Mario Santos Miguel G.