I used to put everything inside useEffect… Until one broken component changed how I think about React. 👀 When I first learned React, useEffect felt like a superpower. Something changed? → useEffect. Need to update a value? → useEffect. Something not working? → Add another dependency. It worked… until it really didn't. One day I was debugging a small component. Nothing complex on the surface. But it had: → Multiple effects fighting each other → Derived state stored AND recalculated → Unexpected re-renders on every tick → Dependency warnings I kept ignoring I sat back and asked: "Why is a 50-line component this painful?" The answer hit me hard. 💡 I was using useEffect as a catch-all. And it was silently making everything harder. Here's the mental model that changed everything: 01. Value computable from props or state? → Calculate it during render. Don't store it again. 02. Logic triggered by a button click? → Put it in the event handler. Not an effect. 03. Just filtering or transforming data? → Do it inline. Render is free. useEffect exists for one purpose — syncing with things outside React: ✦ API calls ✦ Subscriptions ✦ Timers ✦ DOM manipulation ✦ External libraries / WebSockets That's it. The list is short intentionally. The moment I started respecting that boundary… My components became: ✅ Cleaner to read ✅ Easier to debug ✅ More predictable ✅ Faster to ship Sometimes writing better React means writing less useEffect. The best refactor I ever did was deleting three effects — and replacing them with nothing at all. Have you ever refactored a component and removed half your effects? Drop your "aha moment" below 👇 I'd love to read it. #React #ReactJS #JavaScript #FrontendDevelopment #CleanCode #WebDevelopment #SoftwareEngineering #LearningJourney
React useEffect: when to use, when to avoid
More Relevant Posts
-
For a long time, I focused on stopping React from re-rendering. I used "React.memo", "useCallback", and every optimization technique I could find — all to reduce renders. Then I realized something important: Re-renders aren’t usually the real problem. React is actually very fast at rendering. The real issue is doing heavy work during the render phase. For example: const sortedUsers = users.sort((a, b) => a.age - b.age) This sorting runs on every render, which can become expensive as the data grows. A better approach: const sortedUsers = useMemo( () => users.slice().sort((a, b) => a.age - b.age), [users] ) Now the computation only runs when "users" actually changes. The goal isn’t fewer renders. The goal is less work per render. That small mindset shift completely changed how I think about React performance and optimization. Curious to hear from other developers: When did React finally “click” for you? #ReactJS #JavaScript #FrontendDevelopment #WebDevelopment #SoftwareEngineering #Programming #Coding #TechLearning #ReactPerformance #SourceCodeDev
To view or add a comment, sign in
-
-
📌 Today I learned: useReducer — React's powerful alternative to useState When state logic gets complex, useReducer brings structure and clarity. The core concept: ``` const [state, dispatch] = useReducer(reducer, initialState); ``` Instead of directly updating state, you dispatch **actions**. The reducer — a pure function — takes the current state + action and returns the next state. 🔑 Key benefits I discovered: → Centralised logic — all state transitions live in one function → Easier debugging — every state change has an explicit action → Scales better — perfect for complex UI with multiple transitions → More testable — reducers are just pure functions! UseReducer shines when: • You have 3+ related state variables • State updates depend on previous state • Multiple actions affect the same piece of state Think of it like Redux — but built right into React, no extra libraries needed. One day of learning, but the concept already feels foundational. Excited to keep building with it! 🚀 #ReactJS #useReducer #StateManagement #JavaScript #WebDevelopment #FrontendDev #LearningInPublic
To view or add a comment, sign in
-
👉 Stop Overusing useMemo — Do This Instead Most developers learn React optimization like this: useMemo for performance useCallback for functions React.memo for components So we start adding them everywhere. But here’s the truth 👇 useMemo is not a solution. It’s just an optimization tool. And in many cases, it’s not even needed. The real problem is this: 👉 Doing too much work inside render. Example 👇 const sortedUsers = users.sort((a, b) => a.age - b.age) This runs on every render ❌ and mutates the original array. Better 👇 const sortedUsers = useMemo( () => users.slice().sort((a, b) => a.age - b.age), [users] ) But here’s the bigger insight: Don’t jump to useMemo immediately. ✔ Move heavy logic outside render ✔ Preprocess data (API / useEffect) ✔ Keep components simple and focused ✔ Use memoization only when truly needed 💡 The mindset shift: Don’t try to optimize React first. First, reduce the work. Then optimize if necessary. Most performance issues come from what you do inside render — not the render itself. When did you last remove an unnecessary useMemo? 👇 #ReactJS #FrontendDevelopment #WebDevelopment #JavaScript #Programming #Developers
To view or add a comment, sign in
-
Stop Wasting Re-renders: Debounce vs Throttle Have you ever built a search bar that sends an API request on every keystroke? Or added a scroll listener that suddenly makes the UI feel laggy? If you’re not controlling how often a function runs, you’re leaving serious performance gains on the table. Let’s simplify two powerful techniques every frontend developer should know. 👇 ⏱️ Debouncing — “Wait until things stop” Debouncing delays execution until the user stops triggering the event. Think of it like an elevator. It waits for the last person to enter. If someone else jumps in, the timer resets. The elevator moves only when no one else is coming. Best used for: 🔍 Search inputs (run API call after typing stops) 💾 Auto-saving drafts 📏 Window resize handlers 🌊 Throttling — “Run at a steady rate” Throttling ensures a function runs at most once every X milliseconds, no matter how often the event fires. Think of a dripping faucet. No matter how much water pressure there is, it releases one drop at fixed intervals. Best used for: 📜 Infinite scroll checks 🎮 Game controls 🖱️ Mouse / scroll animations 🔍 Quick Comparison Feature Debounce Throttle Goal Run after activity stops Run at fixed intervals Best for Input-heavy events Continuous events Execution Once (after pause) Multiple times (spaced out) 🛠️ Pro Tip In production, don’t reinvent the wheel. Libraries like Lodash make this extremely simple: import { debounce, throttle } from "lodash"; Or build custom React hooks to keep your components clean and optimized. 💬 Question for developers: Which one do you use more in real projects — Debounce or Throttle? Drop your answer in the comments 👇 #WebDevelopment #ReactJS #JavaScript #FrontendDevelopment #PerformanceOptimization #CodingTips #SoftwareEngineering
To view or add a comment, sign in
-
-
What Runs First in React? (Rendering vs useEffect vs useCallback vs useMemo) One day I wrote this small React code just to test my understanding: import { useEffect, useCallback, useMemo } from "react"; export default function App() { useEffect(() => { console.log("useEffect"); }, []); const increment = useCallback(() => { console.log("useCallback"); }, []); const squaredCount = useMemo(() => { console.log("useMemo"); }, []); return ( <div> {console.log("Rendering JSX")} </div> ); } And I asked myself: 👉 What runs first? At first, I guessed randomly. But then I stopped thinking like a coder… and started thinking like React. 🧠 Step 1: React always renders first React’s first job is simple: Build the UI. So this runs first: Rendering JSX Because React must render before doing anything else. 🧠 Step 2: During rendering While React is rendering: • useMemo runs immediately (it calculates something) • useCallback does NOT execute — it only stores the function So you’ll see: useMemo✅ But not: useCallback❌ That function only runs if we call increment() manually. That was my “aha” moment 💡 🧠 Step 3: After rendering → useEffect runs Once the UI is painted, React runs: useEffect Because useEffect always runs after render. ✅ Final Order (on first mount) 1️⃣ Rendering JSX 2️⃣ useMemo 3️⃣ useEffect (useCallback only runs if called) 💡 The lesson I learned Don’t just learn hooks. Learn when they run. Understanding execution order made debugging 10x easier for me. Now whenever something feels “weird” in React, I ask one question: 👉 Is this running during render or after render? Still learning React in human language. 🚀 #JavaScript #FrontendDevelopment #LearningInPublic #CleanCode #ReactJS #useEffect #useMemo #useCallback #FrontendDevelopment #LearningInPublic #JavaScript #WebDevelopment #DeveloperJourney #ReactHook
To view or add a comment, sign in
-
-
Bubbling Concept in React: A Practical Breakdown 🚀 Why Your React Button Click Triggers the Parent (And How to Fix It) One small function can save you from unexpected UI behavior: e.stopPropagation() But what does it actually do? In JavaScript and React, events “bubble up” the DOM tree. That means when you click on a child element, the click event also triggers on its parent elements. Example: <div onClick={() => console.log("Parent clicked")}> <button onClick={() => console.log("Button clicked")}> Click Me </button> </div> If you click the button, the console will log: Button clicked Parent clicked Why? Because the click event bubbles from the button to the parent. 🛑 Preventing Event Bubbling If you want the button click to NOT trigger the parent’s click handler, use: <button onClick={(e) => { e.stopPropagation(); console.log("Button clicked"); }} > Click Me </button> Now only this runs: Button clicked 🛒 Real-World Example Imagine a clickable product card: <div onClick={() => navigate("/product/1")}> <button onClick={addToCart}> Add to Cart </button> </div> Without stopPropagation(), clicking “Add to Cart” will also navigate to the product page. Solution: <button onClick={(e) => { e.stopPropagation(); addToCart(); }} > Add to Cart </button> Now: ✅ The product is added to cart ✅ No unwanted navigation Understanding event propagation is essential for building predictable and clean UI behavior in React applications. Small detail. Big impact. #React #JavaScript #FrontendDevelopment #WebDevelopment
To view or add a comment, sign in
-
🚀 React Hooks Small Projects I recently worked on a few small projects to better understand some important React Hooks. In this video, I demonstrated how these hooks work with simple examples so that beginners can easily understand their usage. 🔹 useState – Used to manage state inside a functional component. It helps update and display dynamic data in the UI. 🔹 useEffect – Used to handle side effects in React applications such as API calls, timers, and updating the DOM when state changes. 🔹 useContext – Helps share data globally across components without passing props manually through every level. 🔹 useReducer – A powerful hook for managing complex state logic, especially when multiple state updates depend on different actions. 🔹 useMemo – Optimizes performance by memoizing expensive calculations so they only run when dependencies change. 🔹 useCallback – Returns a memoized function to prevent unnecessary re-renders when passing functions to child components. These mini projects helped me strengthen my understanding of React Hooks and component optimization techniques. 📌 If you watch the video, you can easily understand how each hook works in a practical way. #ReactJS #ReactHooks #WebDevelopment #MERNStack #JavaScript #FrontendDevelopment #CodingPractice
To view or add a comment, sign in
-
Exploring #ArrowJS , a minimalist approach to modern frontend development ArrowJS is an experimental #JavaScript library for building reactive user interfaces using native JS, without the overhead of traditional frameworks. It challenges the idea that complex tooling is required to build powerful UIs. Key highlights: • ⚡ Ultra-lightweight (~3KB) with zero dependencies • 🧩 No build step, no virtual DOM, no custom templating language • 🔄 Reactive by choice — not by default • 🧠 Leverages modern JavaScript features like template literals, modules, and proxies • 🚀 Fast and simple, with a focus on developer ergonomics The core idea? JavaScript itself has evolved enough that we don’t always need heavy frameworks to create dynamic, performant applications. ArrowJS embraces that philosophy with a “less is more” approach. Worth checking out if you’re interested in lightweight alternatives to React/Vue or exploring new patterns in frontend architecture. #JavaScript #WebDevelopment #Frontend #SoftwareEngineering #Programming #WebDev #DeveloperTools #React #Vue
To view or add a comment, sign in
-
JavaScript events like scroll, resize, and typing can fire hundreds of times per second. If we run heavy functions on every event, the app can become slow and inefficient. Two common solutions to control this are: Debounce and Throttle Debounce Runs the function only after the event stops firing for a specific time. Example: Search input autocomplete. Throttle Runs the function at most once in a fixed time interval, even if the event keeps firing. Example: Scroll event handling. Quick difference: Debounce → waits for user inactivity Throttle → limits how often a function can run Using these techniques improves performance, user experience, and efficiency in real-world applications. Follow for more JavaScript concepts explained visually. 🚀 #javascript #webdevelopment #frontenddeveloper #coding #softwareengineering
To view or add a comment, sign in
-
-
🎯 useEffect vs useLayoutEffect: finally made it clear While learning React hooks, I was confused between useEffect and useLayoutEffect. This visual helped me understand the real difference 👇 👉 useLayoutEffect 1. Runs synchronously 2. Executes before the browser paints the UI 3. Useful when you need to measure or update the DOM before it becomes visible 👉 useEffect 1. Runs asynchronously 2. Executes after the UI is painted 3. Best for API calls, timers, subscriptions, etc. 💡 Key takeaway: 1. useLayoutEffect → blocks paint (use carefully) 2. useEffect → doesn’t block UI (preferred in most cases) Also learned how cleanup (destroy/unmount) works to avoid memory leaks especially with intervals and API calls. Small concepts like this make a big difference in writing better React code #ReactJS #WebDevelopment #Frontend #JavaScript #LearningInPublic #ReactHooks
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