DEV Community

Cover image for Refactoring React: Taming Chaos, One Component at a Time
vigneshiyergithub
vigneshiyergithub

Posted on

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.

Top comments (0)