Logo

dev-resources.site

for different kinds of informations.

Refactoring React: Taming Chaos, One Component at a Time

Published at
1/14/2025
Categories
webdev
react
programming
javascript
Author
vigneshiyergithub
Author
17 person written this
vigneshiyergithub
open
Refactoring React: Taming Chaos, One Component at a Time

Refactoring React code is like turning a chaotic kitchen into a well-organized culinary haven. It’s about improving the structure, maintainability, and performance of your app without changing its functionality. Whether you’re battling bloated components or tangled state logic, a well-planned refactor transforms your codebase into a sleek, efficient machine.

This blog uncovers common refactoring scenarios, provides actionable solutions, and equips you to unlock your React app's true potential.


I. What Is Refactoring and Why Does It Matter?

Refactoring improves your code's structure without changing its functionality. It’s not about fixing bugs or adding features—it’s about making your code better for humans and machines alike.

Why Refactor?

  1. Readability: Debugging code at 3 AM becomes much easier when it reads like a good novel instead of a cryptic puzzle.
  2. Maintainability: A clean codebase saves hours of onboarding time and speeds up updates.
  3. Performance: Cleaner code often translates to faster load times and smoother user experiences.

🛑 Pro Tip: Avoid premature optimization. Refactor when there’s a clear need, like improving developer experience or addressing slow renders.


II. Sniffing Out Code Smells

Code smells are subtle signals of inefficiency or complexity. They’re not errors, but they indicate areas needing improvement.

Common React Code Smells

  1. Bloated Components
    • Problem: A single component handles too many responsibilities, like fetching data, rendering, and handling events.
   function ProductPage() {
     const [data, setData] = useState([]);
     useEffect(() => fetchData(), []);
     const handleAddToCart = () => { ... };
     return (
       <div>
         {data.map(item => <ProductItem key={item.id} item={item} />)}
         <button onClick={handleAddToCart}>Add to Cart</button>
       </div>
     );
   }
Enter fullscreen mode Exit fullscreen mode
  • Solution: Break it into smaller, focused components.
   function ProductPage() {
     return (
       <div>
         <ProductList />
         <CartButton />
       </div>
     );
   }

   function ProductList() {
     const [data, setData] = useState([]);
     useEffect(() => fetchData(), []);
     return data.map(item => <ProductItem key={item.id} item={item} />);
   }

   function CartButton() {
     const handleAddToCart = () => { ... };
     return <button onClick={handleAddToCart}>Add to Cart</button>;
   }
Enter fullscreen mode Exit fullscreen mode
  1. Prop Drilling
    • Problem: Passing props through multiple layers of components.
   <App>
     <ProductList product={product} />
   </App>
Enter fullscreen mode Exit fullscreen mode
  • Solution 1: Use composition.
   <ProductList>
     <ProductItem product={product} />
   </ProductList>
Enter fullscreen mode Exit fullscreen mode
  • Solution 2: Use Context.
   const ProductContext = React.createContext();

   function App() {
     const [product, setProduct] = useState({ id: 1, name: 'Example Product' }); // Example state
     return (
       <ProductContext.Provider value={product}>
         <ProductList />
       </ProductContext.Provider>
     );
   }

   function ProductList() {
     const product = useContext(ProductContext);
     return <ProductItem product={product} />;
   }
Enter fullscreen mode Exit fullscreen mode
  1. Nested Ternary Hell
    • Problem: Complex conditional rendering using nested ternaries.
   return condition1 ? a : condition2 ? b : condition3 ? c : d;
Enter fullscreen mode Exit fullscreen mode
  • Solution: Refactor using helper functions or switch statements.
   function renderContent(condition) {
     switch (condition) {
       case 1: return a;
       case 2: return b;
       case 3: return c;
       default: return d;
     }
   }

   return renderContent(condition);
Enter fullscreen mode Exit fullscreen mode
  1. Duplicate Logic
    • Problem: Repeating the same logic across components.
   function calculateTotal(cart) {
     return cart.reduce((total, item) => total + item.price, 0);
   }
Enter fullscreen mode Exit fullscreen mode
  • Solution: Move shared logic into reusable utilities or custom hooks.
   function calculateTotalPrice(cart) {
     return cart.reduce((total, item) => total + item.price, 0);
   }

   function useTotalPrice(cart) {
     return useMemo(() => calculateTotalPrice(cart), [cart]);
   }
Enter fullscreen mode Exit fullscreen mode
  1. Excessive State
    • Problem: Managing derived state directly.
   const [isLoggedIn, setIsLoggedIn] = useState(user !== null);
Enter fullscreen mode Exit fullscreen mode
  • Solution: Use derived state instead.
   const isLoggedIn = !!user; // Converts 'user' to boolean
Enter fullscreen mode Exit fullscreen mode

III. Simplifying State Management

State management is essential but can quickly become chaotic. Here’s how to simplify it:

Derived State: Calculate, Don’t Store

  • Problem: Storing redundant state.
  • Solution: Calculate derived values directly from the source.
  const [cartItems, setCartItems] = useState([]);
  const totalPrice = cartItems.reduce((total, item) => total + item.price, 0);
Enter fullscreen mode Exit fullscreen mode

Use useReducer for Complex State

  • Problem: Multiple interdependent states.
  • Solution: Use useReducer.
  const initialState = { count: 0 };
  function reducer(state, action) {
    switch (action.type) {
      case 'increment': return { count: state.count + 1 };
      default: return state;
    }
  }
  const [state, dispatch] = useReducer(reducer, initialState);
Enter fullscreen mode Exit fullscreen mode

State Colocation

  • Problem: Global state used for local data.
  • Solution: Move state closer to where it’s needed.
  // Before:
  function App() {
    const [filter, setFilter] = useState('');
    return <ProductList filter={filter} onFilterChange={setFilter} />;
  }

  // After:
  function ProductList() {
    const [filter, setFilter] = useState('');
    return <FilterInput value={filter} onChange={setFilter} />;
  }
Enter fullscreen mode Exit fullscreen mode

IV. Refactoring Components

Components should do one job and do it well. For example:

One Job Per Component

function MemberCard({ member }) {
  return (
    <div>
      <Summary member={member} />
      <SeeMore details={member.details} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

V. Performance Optimization

React Profiler

Use the Profiler to identify bottlenecks. Access it in Developer Tools under "Profiler."

Memoization

Optimize expensive calculations:

const memoizedValue = useMemo(() => calculateExpensiveValue(dependencies), [dependencies]);
Enter fullscreen mode Exit fullscreen mode

Note: Avoid overusing memoization for frequently updated dependencies.


VI. Refactoring for Testability

Write user-centric tests:

test('increments count on button click', () => {
  const { getByText } = render(<Counter />);
  fireEvent.click(getByText(/Increment/i));
  expect(getByText(/Count: 1/)).toBeInTheDocument();
});
Enter fullscreen mode Exit fullscreen mode

VII. Final Touches for Maintainability

  1. Organize by feature:
   /features
     /cart
       Cart.js
       CartItem.js
Enter fullscreen mode Exit fullscreen mode
  1. Use absolute imports:
   import { Cart } from 'features/cart/Cart';
Enter fullscreen mode Exit fullscreen mode

VIII. Cheatsheet

Category Tip
Code Smells Split bloated components; avoid prop drilling.
State Management Use derived state; colocate state.
Performance Use Profiler; optimize Context values.
Testing Test behavior, not implementation details.

react Article's
30 articles in total
React is a JavaScript library for building user interfaces, enabling developers to create reusable components and dynamic web applications.
Favicon
Redux Middleware সম্পর্কে বিস্তারিত আলোচনা
Favicon
POST ABOUT AI'S INCREASING INFLUENCE IN CODING
Favicon
[Boost]
Favicon
🌟 A New Adventure Begins! 🛵🍕
Favicon
From Heist Strategy to React State: How data flows between components
Favicon
Understanding React's useState with Callback Functions: A Deep Dive
Favicon
From Chaos to Clarity: Formatting React Code for a Clean and Readable Codebase
Favicon
Creating a react game on AWS
Favicon
Refactoring React: Taming Chaos, One Component at a Time
Favicon
The Magic of useCallback ✨
Favicon
Show a loading screen when changing pages in Next.js App router
Favicon
How to improve the Frontend part of the project using one button as an example :))))
Favicon
Open-Source TailwindCSS React Color Picker - Zero Dependencies! Perfect for Next.js Projects!
Favicon
Introducing EAS Hosting: Simplified deployment for modern React apps
Favicon
Understanding React's useEffect and Event Listeners: A Deep Dive
Favicon
Recreating the Interswitch Homepage with React and TailwindCSS.
Favicon
How to receive data in form from another component
Favicon
Unlocking the Secrets of React Context: Power, Pitfalls, and Performance
Favicon
"Starting My React Journey"
Favicon
Open-Source React Icon Picker: Lightweight, Customizable, and Built with ShadCN, TailwindCSS. Perfect for Next.js Projects!
Favicon
Dynamically Render Components Based on Configuration
Favicon
Conquer Breakpoints with React's useBreakpoints Hook
Favicon
Using React as Static Files in a Django Application: Step-by-Step Guide
Favicon
Don't copy/paste code you don't understand
Favicon
All-APIs.com: The Ultimate Free REST API Platform for Developers
Favicon
Form-based Dataverse Web Resources with React, Typescript and FluentUI - Part 2
Favicon
Level Up React : Deep Dive into React Elements
Favicon
Building Production-Grade Web Applications with Supabase – Part 1
Favicon
Transform Your Web Development Workflow with These JavaScript Giants
Favicon
Building High-Performance React Native Apps[Tips for Developers]

Featured ones: