🔄 Understanding useReducer in React When managing state in React, most developers start with useState. But as applications grow, state logic can become complex. That’s where useReducer becomes very useful. Think of useReducer as a more structured way to manage state, especially when multiple state changes depend on specific actions. 📌 What is useReducer? useReducer is a React Hook that lets you manage state using a reducer function. It works similarly to how reducers work in Redux. It takes two main things: 1️⃣ A reducer function 2️⃣ An initial state const [state, dispatch] = useReducer(reducer, initialState); state → the current state dispatch → a function used to send actions reducer → decides how state should change 📌 Example const initialState = { count: 0 }; function reducer(state, action) { switch (action.type) { case "increment": return { count: state.count + 1 }; case "decrement": return { count: state.count - 1 }; default: throw new Error("Unknown action"); } } function Counter() { const [state, dispatch] = useReducer(reducer, initialState); return ( <> <p>{state.count}</p> <button onClick={() => dispatch({ type: "increment" })}> Increment </button> <button onClick={() => dispatch({ type: "decrement" })}> Decrement </button> </> ); } Here, instead of directly updating state like setCount, we dispatch actions and the reducer decides how the state should change. 📌 When Should You Use useReducer? ✅ When state logic is complex ✅ When multiple state updates depend on each other ✅ When managing objects or multiple state values ✅ When you want predictable state transitions 💡 Key Insight useReducer separates state logic from UI logic, making your components easier to read, test, and maintain. As React applications grow, this pattern helps keep your state management clean and scalable. 💬 Are you using **useState or useReducer more often in your React projects? #React #FrontendDevelopment #JavaScript #WebDevelopment #ReactHooks #LearningInPublic
Mastering useReducer in React for Complex State Management
More Relevant Posts
-
Most developers use `useMemo()` because they heard it improves performance. But here’s the truth: `useMemo` is not for making your app “faster” magically. It is for avoiding unnecessary work. Imagine your component renders again and again because some state changes. Every render means: * functions run again * calculations run again * arrays/objects get recreated again And sometimes that becomes expensive. Example: You have a list of 10,000 products and you are filtering or sorting them on every render. Without `useMemo`, even if only a button color changes, the filtering logic runs again. const filteredProducts = products.filter(product => product.price > 1000 ) Now imagine this runs on every render. That is unnecessary work. With `useMemo`: const filteredProducts = useMemo(() => { return products.filter(product => product.price > 1000) }, [products]) Now React stores the previous result and only recalculates when `products` changes. That stored value is called memoization. Memoization = remembering the previous result so you don’t have to calculate it again. Why use `useMemo`? ✅ Prevent expensive calculations from running again ✅ Avoid unnecessary re-renders in child components ✅ Improve performance when dealing with large lists, sorting, filtering, heavy computations What problem does it solve? Without `useMemo`: * Slow UI * Lag while typing/searching * Heavy calculations on every render * Child components re-render because new object/array references are created. So if you pass it to a child component, React thinks it changed every time. const user = useMemo(() => ({ name: "Durgesh" }), []) Now the reference stays the same. But there’s a catch 👇 Do NOT use `useMemo` everywhere. `useMemo` itself has a cost. For simple calculations, just write normal code. Rule of thumb: 👉 Use `useMemo` only when: * the calculation is expensive * the value is passed to memoized child components * re-rendering is causing performance issues Don’t optimize first. Measure first. Then optimize. That’s what good React developers do. #react #javascript #webdevelopment #frontend #reactjs #useMemo #performance #coding
To view or add a comment, sign in
-
-
Most developers use `useMemo()` because they heard it improves performance. But here’s the truth: `useMemo` is not for making your app “faster” magically. It is for avoiding unnecessary work. Imagine your component renders again and again because some state changes. Every render means: * functions run again * calculations run again * arrays/objects get recreated again And sometimes that becomes expensive. Example: You have a list of 10,000 products and you are filtering or sorting them on every render. Without `useMemo`, even if only a button color changes, the filtering logic runs again. const filteredProducts = products.filter(product => product.price > 1000 ) Now imagine this runs on every render. That is unnecessary work. With `useMemo`: const filteredProducts = useMemo(() => { return products.filter(product => product.price > 1000) }, [products]) Now React stores the previous result and only recalculates when `products` changes. That stored value is called memoization. Memoization = remembering the previous result so you don’t have to calculate it again. Why use `useMemo`? ✅ Prevent expensive calculations from running again ✅ Avoid unnecessary re-renders in child components ✅ Improve performance when dealing with large lists, sorting, filtering, heavy computations What problem does it solve? Without `useMemo`: * Slow UI * Lag while typing/searching * Heavy calculations on every render * Child components re-render because new object/array references are created. So if you pass it to a child component, React thinks it changed every time. const user = useMemo(() => ({ name: "Durgesh" }), []) Now the reference stays the same. But there’s a catch 👇 Do NOT use `useMemo` everywhere. `useMemo` itself has a cost. For simple calculations, just write normal code. Rule of thumb: 👉 Use `useMemo` only when: * the calculation is expensive * the value is passed to memoized child components * re-rendering is causing performance issues Don’t optimize first. Measure first. Then optimize. That’s what good React developers do. #react #javascript #webdevelopment #frontend #reactjs #useMemo #performance #coding
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
-
-
𝐓𝐡𝐢𝐧𝐤𝐢𝐧𝐠 `React.memo` 𝐦𝐚𝐤𝐞𝐬 𝐲𝐨𝐮𝐫 𝐜𝐨𝐦𝐩𝐨𝐧𝐞𝐧𝐭𝐬 𝐩𝐞𝐫𝐟𝐞𝐜𝐭𝐥𝐲 𝐩𝐞𝐫𝐟𝐨𝐫𝐦𝐚𝐧𝐭? 𝐓𝐡𝐢𝐧𝐤 𝐚𝐠𝐚𝐢𝐧. Many of us reach for `React.memo` to prevent unnecessary re-renders in child components. And it works wonders... most of the time. But here's the catch: `React.memo` performs a shallow comparison of props. If you're passing object, array, or function props, even if their internal values haven't changed, a new reference is created on every parent re-render. This new reference makes `React.memo` think the prop has changed, leading to an unwanted re-render of your memoized child component. ```javascript // Parent component re-renders: const data = { id: 1, name: 'Item' }; // New object reference! <MemoizedChild item={data} /> // Or with a function: const handleClick = () => console.log('clicked'); // New function reference! <MemoizedChild onClick={handleClick} /> ``` The solution? Pair `React.memo` with `useCallback` for functions and `useMemo` for objects/arrays. ```javascript // In Parent component: const memoizedData = useMemo(() => ({ id: 1, name: 'Item' }), []); const memoizedHandleClick = useCallback(() => console.log('clicked'), []); <MemoizedChild item={memoizedData} onClick={memoizedHandleClick} /> ``` This ensures your props maintain the same reference across renders, allowing `React.memo` to truly shine. It's a small detail, but crucial for optimizing complex applications. How aggressively do you memoize in your React apps? Share your go-to strategies! #React #ReactJS #FrontendDevelopment #WebPerformance #JavaScript
To view or add a comment, sign in
-
⚠️ Handling Errors Gracefully in React — A Must-Know for Frontend Developers In real-world apps, things will break. The goal isn’t to avoid errors — it’s to handle them gracefully without crashing the entire UI. That’s where Error Boundaries come in. 👇 --- 🔹 What are Error Boundaries? Error Boundaries are React components that catch JavaScript errors in: ✔ Rendering ✔ Lifecycle methods ✔ Child components They prevent the whole app from crashing and show a fallback UI instead. --- 🔹 How to Create an Error Boundary Error Boundaries are class components (as of now): class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { console.error("Error caught:", error, errorInfo); } render() { if (this.state.hasError) { return <h2>Something went wrong.</h2>; } return this.props.children; } } 🔹 Usage <ErrorBoundary> <MyComponent /> </ErrorBoundary> --- 🔹 Best Practices ✔ Wrap critical UI sections (not the whole app blindly) ✔ Show user-friendly fallback UI (not technical errors) ✔ Log errors to monitoring tools (Sentry, LogRocket) ✔ Combine with try/catch for async logic ✔ Don’t rely on it for event handlers (they’re not covered) --- 🔹 Important Notes ❌ Doesn’t catch errors in: • Event handlers • Async code (e.g. setTimeout, API calls) • Server-side rendering --- 💡 Pro Tip: Error handling is part of user experience. A broken UI loses trust — a graceful fallback builds it. --- Clean UI is good. Resilient UI is better. #reactjs #frontend #webdevelopment #errorhandling #javascript #bestpractices
To view or add a comment, sign in
-
-
React 19 just solved one of the most annoying problems in frontend development. Every React developer has hit this before. You hide a sidebar. The user opens it again. The scroll position is gone. The form fields are cleared. The state has completely reset. You have to rebuild the experience from scratch every time the component mounts. Before React 19, this was the default behavior. When you wrote {isVisible && <Sidebar />}, React unmounted the component when isVisible became false. Every piece of state inside it was destroyed. Effects stopped. Inputs cleared. Scroll position lost. React 19 introduces the Activity component and it changes this completely. import { Activity } from "react"; <Activity mode={isVisible ? "visible" : "hidden"}> <Sidebar /> </Activity> Now when you hide the sidebar: -> State is saved in the background -> Effects pause instead of stopping completely -> Scroll position is preserved -> When it comes back, it restores instantly React hides the component but keeps its state in memory. This matters most for: -> Tab switching where each tab has its own state -> Sidebars and drawers that open and close frequently -> Multi-step forms where going back should restore inputs -> Any component where destroying state creates a bad user experience One small API change. Significantly better user experience with almost no extra code. Are you already on React 19 or still migrating? #React #React19 #FrontendDevelopment #JavaScript #WebDevelopment #Developers #UIEngineering
To view or add a comment, sign in
-
-
For the last decade, the Single Page Application (SPA) was the undisputed king of the frontend. We pushed routing, state management, and rendering all the way to the client. It gave us highly interactive apps, but it also gave us a new problem: Massive JavaScript bundles. Now, we are witnessing a massive architectural shift back to the server. With the rise of React Server Components (RSCs) and frameworks heavily pushing SSR (like Next.js, Nuxt, and SvelteKit), the line between frontend and backend is blurring again. But this isn't just a return to the PHP days. It's a hybrid approach. Here is why this shift is taking over: Zero-Bundle-Size Components: We can now render heavy UI components on the server and ship exactly zero JavaScript to the client for those parts. Better Core Web Vitals: Faster First Contentful Paint (FCP) and Time to Interactive (TTI) because the browser isn't waiting to download and parse megabytes of JS before rendering the page. Direct Backend Access: You can securely query your database directly from a frontend component without building a middleman API layer. We are finally separating the interactive parts of our UI from the static parts at a granular level. The learning curve is steep, and the mental model of "where does this code run?" is shifting, but the performance gains for the end-user are undeniable. #FrontendDevelopment #WebDevelopment #ReactJS #JavaScript #WebPerformance #SoftwareEngineering #SSR #SSG #CSR #SAAS
To view or add a comment, sign in
-
🚀 React Components In React, everything is a component. A component is a small, reusable piece of UI. Instead of writing one big file, we break UI into parts like: 👉 Navbar 👉 Button 👉 Card 👉 Footer 1️⃣ Functional Component (Most Used) function Button() { return <button>Click Me</button>; } Use it like this: <Button /> 2️⃣ Why Components? ✔ Reusable → Write once, use multiple times ✔ Clean code → Split large UI into small parts ✔ Easy to maintain → Update one component, not the whole app 3️⃣ Real Example function UserCard() { return ( <div> <h2>User</h2> <p>Frontend Developer</p> </div> ); } Use multiple times: <UserCard /> <UserCard /> <UserCard /> 4️⃣ Components = Functions React components are just JavaScript functions that return UI. 👉 Input → Props (we’ll cover next) 👉 Output → JSX (UI) 5️⃣ Naming Rule Component names must start with a capital letter ❌ button ✅ Button React apps are just a tree of components working together. #React #JavaScript #Frontend #WebDevelopment #LearningByDoing
To view or add a comment, sign in
-
React.js: The Art of Building Dynamic User Interfaces React.js isn’t just a frontend framework — it’s a UI engine that changed how we think about interactivity, scalability, and performance. Here’s why it continues to dominate frontend engineering 👇 ✅ Component-Driven Architecture: Breaks UIs into reusable, independent components that make apps modular and maintainable. ✅ Virtual DOM for Speed: Instead of re-rendering entire pages, React efficiently updates only what changes — boosting performance. ✅ Declarative Programming: You describe what the UI should look like, not how to build it — React handles the rest. ✅ Hooks & State Management: From useState to useEffect to useContext, React gives developers superpowers for managing logic cleanly. ✅ Ecosystem Depth: Seamless integrations with Redux Toolkit, Next.js, and TypeScript make it enterprise-ready and scalable. 🎯 Why it matters: React isn’t about writing code — it’s about crafting experiences. Every pixel, every component, every state change… tells a story of performance and precision. hashtag #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #NextJS #Redux #FullStackDeveloper #UIUX #PerformanceEngineering
To view or add a comment, sign in
-
-
6 months ago, I opened DevTools in one of my production React apps and said "Why does this take 7 seconds to load?" My Lighthouse score was 48. My initial JS bundle was 2.3MB. The entire app every route, every component, every third-party library was being shipped to the browser before the user saw a single pixel on screen. So I paused everything and spent the next few days doing nothing but profiling, splitting, and refactoring. Here's a glimpse of what I actually did: 1. React.lazy() + Suspense - stopped loading every route upfront. Bundle dropped 83% instantly. 2. Tree shaking lodash - we were importing the whole library for one function. 70KB gone. 3. List virtualization - a 2000-row table was freezing the UI for 4 seconds. react-window fixed it in 30 minutes. 4. Image dimensions - missing width/height was causing brutal layout shifts on every load. 5. Vendor chunk splitting - users were re-downloading React on every deploy. One config change fixed it. The result? Bundle: 2.3MB → 400KB Lighthouse: 48 → 91 Load time cut by 30% No rewrite. No switching frameworks. Just the right fixes, in the right order. I broke down each one in detail - with code snippets, before/after numbers, and the mental model I now use before touching any performance issue. Full blog here 👇 https://lnkd.in/gaw4MNRh If this helped you, share it with a fellow developer who's dealing with a slow React app - it might save them days of debugging. And if you've hit a performance problem I haven't covered here, drop it in the comments. I read every one and it might just become my next post. #React #WebPerformance #Frontend #JavaScript #ReactJS #CoreWebVitals #FrontendDeveloper #SoftwareEngineering
To view or add a comment, sign in
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