React developers: Stop using useState for everything I see this pattern in almost every codebase I audit, and it's killing your app's performance. Here's the problem and 3 better alternatives: THE MISTAKE: javascript const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); // Then managing all 3 states separately... This leads to: Race conditions (data updates before loading finishes) Impossible states (loading=true AND error=true) Scattered logic across multiple useEffects Re-renders you didn't ask for. SOLUTION 1: useReducer for related state javascript const [state, dispatch] = useReducer(reducer, { status: 'idle', // 'loading' | 'success' | 'error' data: null, error: null }); Benefits: One source of truth, impossible states become... impossible. SOLUTION 2: Custom hooks for reusable logic javascript function useFetch(url) { const [state, setState] = useState({ status: 'idle', data: null }); // ... fetch logic return state; } Benefits: Encapsulated, testable, reusable across components. SOLUTION 3: React Query for API calls javascript const { data, isLoading, error } = useQuery('key', fetchFn); Benefits: Caching, automatic refetching, optimistic updates built-in. When to use each? useReducer → Complex state with multiple transitions Custom hooks → Reusable stateful logic React Query → Any API/server state The result? Cleaner code, fewer bugs, better performance. What state management mistakes do you see most often? Drop them in the comments 👇 #React #JavaScript #WebDevelopment #TypeScript #Programming #FrontendDevelopment
React State Management Best Practices
More Relevant Posts
-
🧠 JavaScript is a "Brain" with no "Body." Most developers think console.log, setTimeout, and fetch are part of JavaScript. They aren't. 🤯 Standard JS (ECMAScript) is just a logic engine. It handles variables and loops, but it has no "voice"—it can’t talk to a screen or a network alone. To do anything real, it needs a Host Environment: 🌐 Browsers provide the "limbs" (DOM, Web APIs). ⚙️ Node.js provides the "muscles" (File System, HTTP). I just broke down the "Great JavaScript Identity Crisis" on my blog. Understanding this is the secret to mastering the Event Loop and async performance. Read the full breakdown here: 👇 https://lnkd.in/dSwe-qUb Thanks to Hitesh Choudhary Sir, Piyush Garg, Jay Kadlag #JavaScript #NodeJS #Backend #SoftwareArchitecture #Browser #webapi
To view or add a comment, sign in
-
React Concepts ------------------------- What is Pure Functions? ----------------------- In JavaScript, when functions returns same output when same input is passed is called pure functions. It is like returning same data for same input. So, in pure function output only depend on its input arguments. Pure functions does not produced any side effects as well. Example: -------- addtwoNumber = (a,b)=>{ return a+b; } addtowNumber(2,2); addtowNumber(2,2); addtowNumber(2,2); addtowNumber(2,2); React.memo: ----------- React.memo is a higher-order component (HOC) in React that optimizes the performance of functional components by preventing unnecessary re-renders. It achieves this through a process called memoization. When a functional component is wrapped with React.memo, React will memoize(cache) the rendered output of that component. During subsequent renders, if the props passed to the memoised component are shallowly equal to the props from the previous render, React will skip re-rendering the component and instead reuse the cached output. This can significantly improve performance, especially for components that are frequently re-rendered but whose props often remain the same. HOC: ---- A Higher-Order Component (HOC) in React is an advanced techniue for reusing component logic. It is a function that takes a component as an argument and returns a new, enhanced component. Lazy Loading in React: ---------------------- Lazy loading is a way to delay loading certain parts of the application until they are actually needed. React provides the React.lazy function, which allows you to define components that are loaded dynamically. What is Code Splitting? ----------------------- Code splitting is a technique that breaks down a large JavaScript bundle into smaller chunks that are loaded on demand. Instead of loading the entire application at once, only the code needed for the current view is fetched. This approach reduces initial load times and allows the application to load better. Error boundaries -------------------------- Error boundaries in React are components designed to catch JavaScript error that aoccur within their child component tree, log those errors, and display a fallback UI instead of crashing the entire application. They act as a safety net, preventing unhandled error in a part of the UI from affecting the rest of the application.
To view or add a comment, sign in
-
🚀 Understanding JSX in React — Syntax & Rules Simplified! If you're working with React, JSX is everywhere. But JSX is not HTML—it’s JavaScript with a syntax extension. 💡 What is JSX? JSX (JavaScript XML) lets you write UI like this: const element = <h1>Hello, World!</h1>; 👉 Behind the scenes, React converts this into: React.createElement("h1", null, "Hello, World!"); ⚙️ How JSX works 👉 JSX is compiled into JavaScript 👉 It describes what the UI should look like 👉 React uses it to create Virtual DOM 🧠 Key Rules of JSX (Very Important!) 🔹 1. Return a single parent element // ❌ Wrong return ( <h1>Hello</h1> <p>World</p> ); // ✅ Correct return ( <> <h1>Hello</h1> <p>World</p> </> ); 🔹 2. Use className instead of class <div className="container"></div> 🔹 3. JavaScript inside {} const name = "React"; <h1>Hello {name}</h1> 🔹 4. Self-closing tags <img src="image.png" /> 🔹 5. Inline styles as objects <div style={{ color: "red" }}></div> 🧩 Real-world use cases ✔ Building UI components ✔ Rendering dynamic data ✔ Conditional UI rendering ✔ Mapping lists 🔥 Best Practices (Most developers miss this!) ✅ Keep JSX clean and readable ✅ Extract complex logic outside JSX ✅ Use fragments instead of unnecessary divs ❌ Avoid writing heavy logic inside JSX ⚠️ Common Mistake // ❌ Too much logic inside JSX return <h1>{user.isLoggedIn ? "Welcome" : "Login"}</h1>; 👉 Fine for small cases, but extract logic for complex UI 💬 Pro Insight JSX is not about writing HTML in JS— 👉 It’s about describing UI in a declarative way 📌 Save this post & follow for more deep frontend insights! 📅 Day 6/100 #ReactJS #FrontendDevelopment #JavaScript #JSX #WebDevelopment #SoftwareEngineering #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
Using useEffect for every API call in React. It worked. But it was a mess. 😅 This is what my code looked like: const UserList = () => { const [users, setUsers] = useState([]) const [loading, setLoading] = useState(false) const [error, setError] = useState(null) useEffect(() => { setLoading(true) fetchUsers() .then(data => setUsers(data)) .catch(err => setError(err)) .finally(() => setLoading(false)) }, []) if (loading) return <div>Loading...</div> if (error) return <div>Error!</div> return users.map(user => <UserCard user={user} />) } 3 useState calls. Manual loading/error handling. No caching. No refetching. Code repeated in every component. 😔 Then I discovered React Query: const UserList = () => { const { data, isLoading, error } = useQuery({ queryKey: ['users'], queryFn: fetchUsers }) if (isLoading) return <div>Loading...</div> if (error) return <div>Error!</div> return data.map(user => <UserCard user={user} />) } Same result. But: ✅ No manual loading state ✅ No manual error handling ✅ Automatic caching ✅ Background refetching ✅ 70% less code Rule I follow now: → Server state = React Query → UI state = useState → Complex state = useReducer Wish I knew this earlier. 🚀 Are you still using useEffect for API calls? Comment below! 👇 #ReactJS #JavaScript #Frontend #WebDevelopment #ReactQuery #CleanCode
To view or add a comment, sign in
-
-
I was using useEffect for every API call in React. It worked. But it was a mess. 😅 This is what my code looked like: const UserList = () => { const [users, setUsers] = useState([]) const [loading, setLoading] = useState(false) const [error, setError] = useState(null) useEffect(() => { setLoading(true) fetchUsers() .then(data => setUsers(data)) .catch(err => setError(err)) .finally(() => setLoading(false)) }, []) if (loading) return <div>Loading...</div> if (error) return <div>Error!</div> return users.map(user => <UserCard user={user} />) } 3 useState calls. Manual loading/error handling. No caching. No refetching. Code repeated in every component. 😔 Then I discovered React Query: const UserList = () => { const { data, isLoading, error } = useQuery({ queryKey: ['users'], queryFn: fetchUsers }) if (isLoading) return <div>Loading...</div> if (error) return <div>Error!</div> return data.map(user => <UserCard user={user} />) } Same result. But: ✅ No manual loading state ✅ No manual error handling ✅ Automatic caching ✅ Background refetching ✅ 70% less code Rule I follow now: → Server state = React Query → UI state = useState → Complex state = useReducer Wish I knew this earlier. 🚀 Are you still using useEffect for API calls? Comment below! 👇 #ReactJS #JavaScript #Frontend #WebDevelopment #ReactQuery #CleanCode
To view or add a comment, sign in
-
-
🤔 Ever had code like user.address.city crash your app just because address was missing? That is exactly the problem optional chaining helps solve. 🧠 JavaScript interview question What are optional chaining and nullish coalescing operators? ✅ Short answer ?. lets you safely access a property, call a method, or read an index when the value might be null or undefined. ?? gives you a fallback value, but only when the left side is null or undefined. Together, they help you safely read nested data without accidentally replacing valid values like 0 or "". 🔍 Optional chaining: ?. Without it, deeply nested access can throw: const city = user.address.city; // crash if address is missing With optional chaining: const city = user?.address?.city; Now if user or address is missing, the expression returns undefined instead of throwing. It also works with: properties → obj?.prop arrays → arr?.[0] method calls → obj.method?.() So this is valid too: button.onclick?.(event); If onclick does not exist, nothing runs and no error is thrown. 🔍 Nullish coalescing: ?? Use it when you want a default only for missing values: const name = user?.name ?? "Anonymous"; That means: if user?.name is null or undefined → use "Anonymous" if it is "", 0, or false → keep the original value That is the key difference from ||. ⚠️ Common mistake const count = 0; console.log(count || 10); // 10 console.log(count ?? 10); // 0 || treats all falsy values as missing. ?? treats only null and undefined as missing. 🔗 Using them together This is a very common real-world pattern: const zip = user?.address?.zip ?? "00000"; Meaning: try to safely read zip, and if it does not exist, use a fallback. 📌 Best way to think about it ?. = “Does this exist?” ?? = “If not, use this instead.” One prevents crashes. The other gives safer defaults. That combo shows up everywhere in modern JavaScript, especially when working with API responses, forms, and optional config objects. #JavaScript #WebDevelopment #FrontendDevelopment #SoftwareEngineering #CodingInterview #JavaScriptTips #JSInterviewPrep #FrontendEngineer #WebDev #Programming
To view or add a comment, sign in
-
In React, a reusable input component acts as a controlled wrapper around a native <input>. It takes props from its parent (like value, onChange, label and error) to keep data flow predictable and consistent. Here’s the key flow: - The parent form component manages the state (formeData, errors) - Each child component (e.g., input field) receives its value and event handler through props. -When a user types, the onChange event triggers a state update in the parent. This structure separates responsibilities where the form handles data and validation while the input handles display and interaction. Below diagram illustrates the controlled data flow loop in React forms. At the top, the parent component (form) holds the state, which serves as the single source of truth for the form data. The state’s value and an onChange handler are passed downward to the child component (<InputField>), which displays the value and triggers the onChange event when the user types. This event flows upward to the parent, asking it to update its state based on the user’s input. Once the state is updated, React rerenders the UI, sending the latest value back down to the input field, completing the loop. This continuous cycle ensures that the parent’s state always controls the form, keeping the interface predictable, consistent, and synchronized with user interactions. #react #frontend #javascript #reactjs #nextjs #software #webdevelopment
To view or add a comment, sign in
-
-
⚠️ React developers: Your dropdown isn't broken. Your DOM tree is lying to you. Being a full-stack developer means you're basically a one-person circus — frontend, backend, auth flows, DB schema, API contracts, real-time sync, pagination logic, timezone handling, and about 47 other things before your first coffee. And then... a dropdown misbehaves. You've set z-index: 9999. You're on Tailwind's z-50. You've stared at the DevTools inspector like it owes you money. And that dropdown is still hiding behind a card, a modal, or some random parent wrapper. Here's what's actually going on — and it's not your fault. The real culprit: CSS Stacking Contexts When a parent element carries overflow: hidden, transform, opacity < 1, or will-change, it silently creates a new stacking context. Your z-index is now scoped within that parent only — not the full document. So z-index: 9999 inside a transformed card still loses to z-index: 1 outside it. You're not fighting the dropdown. You're fighting the DOM tree itself. The fix that actually holds up: React Portal dropdown.jsx file - import ReactDOM from 'react-dom'; const Dropdown = ({ children, style }) => { return ReactDOM.createPortal( <div style={style}>{children}</div>, document.body ); }; createPortal() renders your dropdown directly at document.body completely outside every parent's stacking context. No more overflow battles. No more z-index wars. But here's the catch nobody mentions: Since the dropdown is now detached from its trigger element, you have to manually position it. Use getBoundingClientRect() on the trigger button to calculate exact top/left coordinates and inject them as inline styles. Don't skip this step or your dropdown will haunt the top-left corner of the screen. This is how modals, tooltips, and production-grade dropdowns are built. This is the kind of thing no tutorial warns you about. You only discover it at 11 PM when everything else is done and this one tiny thing refuses to fall in line. 🧠 Lesson Not every bug is about syntax. Some are about understanding how the browser actually works. And that’s the difference between: fixing issues randomly vs solving them once and for all If this saved you a late-night debugging session — pass it on..... 📌 MDN — https://lnkd.in/dD5HU5ZB 📌 React Docs — https://lnkd.in/dJB8NW7R 📌 Deep dive on z-index & stacking — https://lnkd.in/dCVgYX45 #ReactJS #FullStackDev #WebDevelopment #FrontendEngineering #TailwindCSS #ReactPortal #JavaScriptTips #UIEngineering #CSSDeepDive #BuildInPublic
To view or add a comment, sign in
-
-
🚀 Understanding Dependencies in JavaScript: "dependencies", "devDependencies", and "peerDependencies" While working with Node.js or modern frontend frameworks like React or Next.js, three types of dependencies commonly appear in the "package.json" file: - "dependencies" - "devDependencies" - "peerDependencies" --- 📦 1. "dependencies" These are packages that an application needs to run in production. If the application directly uses a library during runtime (when users interact with the application), it should be included in "dependencies". Examples: - React - Axios - Express "dependencies": { "react": "^18.2.0", "axios": "^1.6.0" } When the project is installed using: npm install these packages are installed because they are required for the application to function properly. --- 🛠️ 2. "devDependencies" These packages are only required during development, not when the application runs in production. They assist developers in writing, testing, and building the code. Common examples include: - Testing libraries - Linters - Build tools - TypeScript "devDependencies": { "typescript": "^5.0.0", "eslint": "^8.0.0", "jest": "^29.0.0" } In many production environments, only "dependencies" are installed, which helps keep the production build smaller and more efficient. --- 🤝 3. "peerDependencies" "peerDependencies" work differently. They are used when a package expects the consuming project to provide a specific dependency. This situation commonly appears when building libraries, plugins, or reusable components. For example, while building a React component library, installing another copy of React inside the library could create conflicts. Instead, the library expects the parent project to already have React installed. "peerDependencies": { "react": ">=18" } This approach helps ensure: - No duplicate versions of React - Better compatibility with the host project
To view or add a comment, sign in
-
-
𝑵𝑶𝑫𝑬.𝒋𝒔 𝑭𝑨𝑸 𝐐: 𝐖𝐡𝐚𝐭 𝐢𝐬 𝐍𝐨𝐝𝐞.𝐣𝐬? Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine, which takes JavaScript code and executes it directly on the computer's operating system. It enables developers to run JavaScript code on the server-side, contrary to the traditional approach of executing JavaScript in the browser. 𝐐. 𝐖𝐡𝐚𝐭 𝐢𝐬 𝐕𝟖 ? V8 is Google’s open-source, high-performance JavaScript engine. It is written in C++ and is the same engine that powers the Google Chrome browser. 𝑰𝒏 𝒔𝒊𝒎𝒑𝒍𝒆 𝒕𝒆𝒓𝒎𝒔: JavaScript is a high-level language that computers don't naturally "speak." V8 acts as the translator that turns your JavaScript code into something the computer's processor can actually execute. 𝙆𝙚𝙮 𝙍𝙤𝙡𝙚𝙨 𝙤𝙛 𝙑8 𝙞𝙣 𝙉𝙤𝙙𝙚.𝙟𝙨 • 𝑪𝒐𝒎𝒑𝒊𝒍𝒂𝒕𝒊𝒐𝒏: V8 doesn't just interpret code line-by-line (which is slow). It uses a process called Just-In-Time (JIT) Compilation to compile JavaScript directly into native machine code before executing it. • 𝑴𝒆𝒎𝒐𝒓𝒚 𝑴𝒂𝒏𝒂𝒈𝒆𝒎𝒆𝒏𝒕: It handles the call stack and the "Heap" (where objects are stored). • 𝑮𝒂𝒓𝒃𝒂𝒈𝒆 𝑪𝒐𝒍𝒍𝒆𝒄𝒕𝒊𝒐𝒏: V8 automatically identifies and clears out objects that are no longer being used to prevent memory leaks. 𝐐. 𝐖𝐡𝐚𝐭 𝐢𝐬 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐑𝐮𝐧𝐭𝐢𝐦𝐞 𝐄𝐧𝐯𝐢𝐫𝐨𝐧𝐦𝐞𝐧𝐭 ? A runtime environment provides all the necessary components to execute and run code. In the case of JavaScript, the browser acts as the runtime environment. However, with Node.js, developers can execute JavaScript outside the browser, allowing them to access resources and perform tasks typically reserved for server-side programming languages. 𝐐. 𝐖𝐡𝐲 𝐰𝐚𝐬 𝐍𝐨𝐝𝐞.𝐣𝐬 𝐂𝐫𝐞𝐚𝐭𝐞𝐝 ? 𝑻𝒉𝒆 𝑷𝒓𝒐𝒃𝒍𝒆𝒎: 𝑩𝒍𝒐𝒄𝒌𝒊𝒏𝒈 𝑰/𝑶: In traditional servers, every time a user made a request (like asking for a file or a database record), the server would spawn a new thread. ➛ If that thread had to wait for a database to respond, it would just "sit there" doing nothing (Blocking). ➛ As more users connected, the server would run out of RAM because each thread consumes memory. 𝑻𝒉𝒆 𝑪𝒐𝒓𝒆 𝑷𝒉𝒊𝒍𝒐𝒔𝒐𝒑𝒉𝒚: Node.js was created based on three main pillars: 1. 𝑵𝒐𝒏-𝑩𝒍𝒐𝒄𝒌𝒊𝒏𝒈 𝑰/𝑶: Instead of waiting for a database to return data, Node.js sends the request and moves on to the next task immediately. When the data is ready, a "callback" is triggered to handle it. 2. 𝑺𝒊𝒏𝒈𝒍𝒆-𝑻𝒉𝒓𝒆𝒂𝒅𝒆𝒅 𝑬𝒗𝒆𝒏𝒕 𝑳𝒐𝒐𝒑: Node.js uses a single main thread to handle all requests. This makes it extremely lightweight and efficient for I/O-intensive applications (like chat apps, streaming, or real-time tools). 3. 𝑼𝒏𝒊𝒇𝒊𝒆𝒅 𝑳𝒂𝒏𝒈𝒖𝒂𝒈𝒆 (𝑭𝒖𝒍𝒍-𝑺𝒕𝒂𝒄𝒌): By bringing JavaScript to the server, Node.js allowed developers to use the same language for both the frontend and the backend. This reduced the "context switching" for developers and made it easier to share code between the two sides.
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
It's actually a good approach