useEffect is the most abused hook in React. Here's what to use instead. I've reviewed hundreds of React codebases. useEffect is in the wrong place in about 60% of them. Not because developers are careless. Because nobody explained when NOT to use it. Here are the cases I see constantly — and what actually belongs there: // ❌ Case 1: Deriving state useEffect(() => { setFullName(`${firstName} ${lastName}`) }, [firstName, lastName]) // ✅ Just compute it const fullName = `${firstName} ${lastName}` No state. No effect. No re-render bug. // ❌ Case 2: Fetching data on mount (with App Router) useEffect(() => { fetch('/api/user').then(...) }, []) // ✅ Use a Server Component or TanStack Query // Data fetching is not a side effect in modern React // ❌ Case 3: Syncing two pieces of state useEffect(() => { if (selectedId) setDetails(getDetails(selectedId)) }, [selectedId]) // ✅ Derive during render const details = selectedId ? getDetails(selectedId) : null The React team has said explicitly: if you're using useEffect to sync state with other state, you probably have one piece of state too many. useEffect is for: → Connecting to external systems (WebSocket, third-party libraries, browser APIs) → Setting up subscriptions → Manual DOM manipulation That's mostly it. If you're using useEffect for anything that feels like when X changes, update Y, there's almost certainly a cleaner way. What's the strangest useEffect usage you've come across? #React #JavaScript #TypeScript #FrontendDevelopment #WebDevelopment
Muhammad Mubeen Yasin’s Post
More Relevant Posts
-
Stop spamming "use client" everywhere in Next.js — it's silently killing your React Server Components. 👇 Most Next.js devs are accidentally turning off React Server Components — and don't even know it. The moment you add "use client" to a parent component, every child inside it becomes a client component too. No async data fetching. No streaming. No zero-JS HTML. Just a bigger JS bundle landing in your user's browser. ❌ Why it hurts Adding "use client" to a parent component converts the entire subtree into a client bundle. Every child component, every import — all sent to the browser. You lose async data fetching, streaming, and zero-JS rendering on the server. Most devs add it to silence hydration errors without understanding the blast radius. ✅ The right mental model Push "use client" as deep as possible — to the leaf component that actually needs state or browser APIs (onClick, useState, useEffect). Keep pages and layouts as Server Components. This way Next.js can stream HTML fast, skip JS for static parts, and still hydrate only the interactive pieces. I've seen this on almost every App Router codebase — "use client" at the top of the page, layout, or a shared wrapper. One line, silently destroying the entire RSC architecture. The fix? Push "use client" to the leaf — the single component that actually uses useState, onClick, or a browser API. Keep everything above it on the server. Golden rule: "use client" is a boundary, not a decorator. Place it at the edge, not the root. #NextJS #ReactJS #WebDevelopment #JavaScript #TypeScript #ReactServerComponents #AppRouter #FrontendDeveloper #SoftwareEngineer #Programming #CleanCode #100DaysOfCode #WebDev #NextJS14 #React19 #ServerComponents #JSPerformance #FrontendArchitecture #CodeQuality #TechTips
To view or add a comment, sign in
-
-
Every Node.js app eventually hits "I need rate limiting." You Google it. You find express-rate-limit. You install it. Then you realize: → It only works with Express → You also have a Next.js Edge route → And a React frontend making too many API calls → Oh, and you need Redis for production So now you're stitching 4 different libraries together. 😅 That's exactly why I built limiterx. One package. Every runtime. ✅ Express, Koa, Node HTTP ✅ Next.js API routes + Edge Middleware ✅ React hook for client-side throttling ✅ Fetch + Axios wrappers ✅ Redis store out of the box ✅ 3 algorithms: fixed-window, sliding-window, token-bucket And it ships with zero runtime dependencies. Tree-shakeable. TypeScript-first. Works on Node, browsers, Edge, and Bun. Getting started is literally this: npm install limiterx Then: app.use(rateLimitExpress({ max: 100, window: '15m' })) That's it. If you're building anything in JS/TS that talks to an API — this is for you. 🔗 npm: https://lnkd.in/gxbf3Jxt 🐙 GitHub: https://lnkd.in/gxt-RAi3 Drop a ⭐ if this saves you a headache. And share with anyone building Node apps — they'll thank you. #nodejs #javascript #typescript #webdev #opensource #ratelimiting #nextjs #developer
To view or add a comment, sign in
-
I struggled with this React concept more than I expected… 👇 👉 Why are my API calls running twice? ⚙️ What you’ll notice You open your network tab and suddenly see this: api/me → called twice api/roles → called twice api/permissions → called twice Just like in the screenshot 👇 Same request, duplicated… again and again. ⚙️ What’s actually happening In React (development mode), if your app is wrapped in Strict Mode, React will run effects twice on purpose. useEffect(() => { fetch("/api/users") .then(res => res.json()) .then(setUsers); }, []); Even though it looks like it should run once… it doesn’t (in dev). 🧠 What’s going on under the hood React basically does a quick cycle: mount → unmount → remount Why? To catch hidden side effects To check if cleanup is handled properly To make sure your logic doesn’t break on re-renders So if your API call runs twice, React is just making sure your code can handle it. 💡 The important part This only happens in development Production behaves normally (runs once) Your side effects should be safe to run multiple times 🚀 Final thought If your network tab looks “noisy” like the screenshot, it’s not React being broken — it’s React being careful. And once you understand this, debugging becomes a lot less confusing. #React #Frontend #JavaScript #WebDevelopment #ReactJS #SoftwareEngineering
To view or add a comment, sign in
-
Most React devs know when to use useLayoutEffect. Almost none can explain why it behaves differently. The answer lives inside the commit phase. React's update cycle has two big stages: render (reconcile, diff, no DOM writes) and commit (apply changes, run effects). Commit itself splits into 3 sub-phases: → Before Mutation — read DOM snapshots before anything changes → Mutation — insert, update, remove DOM nodes → Layout — refs attached, useLayoutEffect fires here, synchronously useEffect never runs in the Layout pass. During reconciliation, React builds an Effect List — fiber nodes tagged with pending work. Fibers marked HookLayout flush during the Layout sub-phase. Fibers marked HookPassive get handed to the scheduler and run after the browser paints. React docs put it directly: "React guarantees that the code inside useLayoutEffect and any state updates scheduled inside it will be processed before the browser repaints the screen." Classic case where this matters: tooltip positioning. With useEffect, users catch a flicker — the tooltip renders in the wrong spot, then jumps. With useLayoutEffect, both renders complete before any pixel changes on screen. The tradeoff: useLayoutEffect blocks paint. Use it only when you need to measure or mutate the DOM before the user sees the frame. Data fetching, subscriptions, analytics — those belong in useEffect. One gotcha: useLayoutEffect is a no-op in SSR. React will warn you. Guard with typeof window !== 'undefined' or default to useEffect in universal code. #frontend #reactjs #javascript #typescript #frontenddevelopment #softwareengineering #webdevelopment
To view or add a comment, sign in
-
-
CORS becomes very easy to understand with one real example. Imagine this: You’re building a React app on http://localhost:3000 Your backend API is running on http://localhost:8000 From your frontend, you make a request: fetch("http://localhost:8000/api/profile") Looks normal, right? But the browser sees this as: Frontend → localhost:3000 Backend → localhost:8000 Same machine. Same localhost. Different port. And that different port is enough for the browser to say: “Hold on — this is a different origin. I need permission first.” So before sending the real request, the browser asks your backend: “Is localhost:3000 allowed to access you?” That’s the CORS check. If your backend responds with: Access-Control-Allow-Origin: http://localhost:3000 The browser allows the request. If not, it blocks it and throws the CORS error. That’s why this fails: fetch("http://localhost:8000/api/profile") Not because your API is broken. Not because React failed. But because the browser is protecting the user. And that’s the key thing most beginners miss: CORS is not a server error. It’s the browser asking the server for permission. Once you understand that, CORS stops feeling random. #Frontend #WebDevelopment #JavaScript #ReactJS #NodeJS #FullStack #SoftwareEngineering #Developers #TechConcepts
To view or add a comment, sign in
-
-
🚀 React Quick Revision Here are some important React concepts explained in short 🔹 1) Which is the entry file in React? 👉 In most React apps, the entry file is index.js / main.jsx 👉 It is responsible for rendering the root component: ReactDOM.createRoot(document.getElementById("root")).render(<App />); 🔹 2) What is the datatype of useEffect second argument? 👉 It is an Array useEffect(() => {}, [dependency]); 👉 This array is called the dependency array and controls when the effect runs. 🔹 3) useState syntax explanation (arrow understanding) const [state, setState] = useState(initialValue); 👉 Breakdown: const → variable declaration [state, setState] → array destructuring useState() → hook function setState → function to update state 👉 Arrow meaning: setState is a function → used to update value 🔹 4) Difference between Tag and Component 👉 Tag (HTML Element): <div>Hello</div> Built-in HTML element Lowercase naming 👉 Component (React): <MyComponent /> Custom reusable function Always starts with uppercase Returns JSX #ReactJS #FrontendDeveloper #JavaScript #WebDevelopment #Learning
To view or add a comment, sign in
-
🚀 Why useState is a Game-Changer in React. let's breakdown this 👇 💡 What is useState? "useState" is a React Hook that allows you to store and manage dynamic data (state) inside functional components. Without it, your UI wouldn’t respond to user input. 📱 Real-Time Example: Form Input & Validation Let’s take a simple login form 👇 import React, { useState } from "react"; function LoginForm() { const [email, setEmail] = useState(""); const [error, setError] = useState(""); const handleSubmit = (e) => { e.preventDefault(); if (!email.includes("@")) { setError("Please enter a valid email address"); } else { setError(""); alert("Form submitted successfully!"); } }; return ( <form onSubmit={handleSubmit}> <input type="text" placeholder="Enter email" value={email} onChange={(e) => setEmail(e.target.value)} /> {error && <p style={{ color: "red" }}>{error}</p>} <button type="submit">Submit</button> </form> ); } export default LoginForm 🧠 What’s happening here? - "email" → stores user input - "setEmail" → updates input as the user types - "error" → stores validation message - "setError" → shows/hides error instantly useState is what connects user actions to UI behavior. It ensures your forms are not just functional, but smart and responsible 💬 Have you implemented form validation using useState? What challenges did you face? #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #Coding
To view or add a comment, sign in
-
React re-render fixes React performance tips I learned the hard way over 8 years. Not from docs. From debugging slow UIs in production with real users waiting. Here are 5 things I wish someone told me on day one: 𝟭. Stop putting everything in one Context. I've seen apps where one global context holds auth, theme, user data, and cart state. Every update re-renders EVERYTHING. Split your contexts by update frequency. Auth rarely changes. Cart changes constantly. They shouldn't live together. 𝟮. useMemo and useCallback are not free. They have a cost — memory and comparison overhead. I've seen devs wrap every single function in useCallback "for performance." If the component isn't actually re-rendering unnecessarily, you're adding complexity for zero benefit. Profile first. Memoize second. 𝟯. Lazy load below the fold. On a banking platform, we had 40+ components loading on the dashboard. Users only saw 5 on first paint. We implemented React.lazy() + Suspense for everything below the fold. Page load dropped 35%. The trick: wrap lazy components in proper error boundaries, not just Suspense. 𝟰. Key prop abuse kills performance silently. Using array index as key in a list that reorders? React destroys and recreates every DOM node instead of reordering them. On a data grid with 500+ rows, this was the difference between a 200ms and 3-second re-render. Use stable, unique IDs. 𝟱. State colocation > state management libraries. Before reaching for Redux, ask: does this state need to be global? I've refactored apps where 60% of Redux state was only used by one component. Moving state closer to where it's used eliminated 45% of unnecessary re-renders in one project. The fastest React app isn't the one with the cleverest optimization. It's the one that avoids unnecessary work in the first place. What's a React performance lesson you learned the hard way? #ReactJS #JavaScript #FrontendDevelopment #WebPerformance #TypeScript #SoftwareEngineering
To view or add a comment, sign in
-
Next.js 14: To Client or To Server? That is the question. 🚀 As Front-End Developers working with Next.js, we often face the dilemma: Should this component be a Server Component (default) or a Client Component ("use client")? After working on various projects, I’ve found that the "Default to Server" approach is a game-changer for performance. Here is my quick cheat sheet: 🌐 Server Components (The Powerhouse) Best for: Data fetching directly from the database or external APIs. Why? It keeps large dependencies on the server, resulting in a much smaller JavaScript bundle for the user. Security: Keeps sensitive keys and logic away from the browser. 🖱️ Client Components (The Interaction) Best for: Interactivity (onClick, onChange) and browser-only APIs like localStorage or window. Why? Essential when you need to use React Hooks like useState or useEffect. Pro Tip: Keep your "use client" components at the leaf level (lowest possible part of the tree) to keep the rest of your app fast and SEO-friendly. The goal isn't just to make it work—it's to make it fast. ⚡ What is your go-to strategy for balancing Server and Client components in your React projects? Let's discuss in the comments! 👇 #ReactJS #NextJS #WebDevelopment #FrontendDeveloper #JavaScript #CodingTips #TechCommunity
To view or add a comment, sign in
-
-
🚀 I just published my first open-source npm package: react-permissions-solution https://lnkd.in/dPkwBb4Q Every React app with user roles ends up with the same mess: ❌ {user.role === 'admin' && <DeleteButton />} ❌ Logic duplicated across 50+ components ❌ Change a role? Good luck finding every condition So I built a clean, declarative solution. ✅ One source of truth for all your access control ✅ Works with any backend — hardcoded or API-driven ✅ TypeScript-first with full type safety ✅ Wildcard support (* , read:* , *:posts) ✅ Zero dependencies — ~2KB minzipped The API is simple by design: // wrap your app once <PermissionsProvider role={user.role} permissions={ROLES[user.role]}> <App /> </PermissionsProvider> // use anywhere <Can do="delete" on="posts"> <DeleteButton /> </Can> // or in logic const { can, is } = usePermissions() if (can('delete', 'posts')) { ... } if (is('admin')) { ... } Supports 3 APIs for different situations: → <Can> component for UI rendering → usePermissions() hook for logic & event handlers → withPermission() HOC for protecting entire pages 📦 npm install react-permissions-solution This is my first published package — feedback, stars, and PRs are very welcome 🙏 #ReactJS #OpenSource #TypeScript #Frontend #NPM #WebDev #JavaScript
To view or add a comment, sign in
-
More from this author
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