Friday, September 22, 2023

10 Anti-Patterns in React: Quick Tips and Tricks for Better Code

Introduction:

React.js is a widely embraced UI library, known for its power and flexibility. However, this very flexibility sometimes leads developers into common pitfalls, resulting in anti-patterns. In this article, we'll delve into these 10 React anti-patterns and offer practical tips to enhance your code quality.

1. One Overly Large Component:

One common mistake when starting a new React app is creating one big component that handles everything. This approach makes it difficult to understand, refactor, and test the codebase effectively. To address this issue, consider refactoring your code into reusable components. Tools like VS Code's "Glean" extension can automate this process by extracting highlighted code into separate components with required props.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Before refactoring
class App extends React.Component {
  render() {
    return (
      <div>
        {/* Many lines of code */}
      </div>
    );
  }
}

// After refactoring
class Header extends React.Component {
  render() {
    return (
      <header>
        {/* Header content */}
      </header>
    );
  }
}

class Sidebar extends React.Component {
  render() {
    return (
      <aside>
        {/* Sidebar content */}
      </aside>
    );
  }
}

class App extends React.Component {
  render() {
    return (
      <div>
        <Header />
        <Sidebar />
        {/* Main content */}
      </div>
    );
  }
}

2. Nesting Components:

Nesting child components within parent components may seem intuitive but comes with performance issues due to redefining the child component every time the parent renders. To avoid this problem, either define the child component outside of the parent or pass functions as props instead of defining them inside the parent component.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Defining child component outside of the parent
function ChildComponent(props) {
  return (
    // Child component JSX
  );
}

class ParentComponent extends React.Component {
  render() {
    return (
      <div>
        <ChildComponent />
      </div>
    );
  }
}

// Passing functions as props
class ParentComponent extends React.Component {
  handleClick() {
    // Handle click event
  }

  render() {
    return (
      <div>
        <ChildComponent onClick={this.handleClick} />
      </div>
    );
  }
}

3. Rerunning Expensive Calculations:

When dealing with state changes that require expensive calculations each time they occur, it's important not to rerun those calculations unnecessarily. The `useMemo` hook can help optimize such scenarios by remembering previous values and only recalculating when necessary.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import { useMemo } from 'react';

function ExpensiveCalculationComponent({ data }) {
  const expensiveResult = useMemo(() => {
    // Expensive calculations based on 'data'
    return result;
  }, [data]);

  return (
    // Render component with 'expensiveResult'
  );
}

4a. Returning Multiple Sibling Elements:

React requires each component to have a single root element when returning JSX markup from a function/component.

Instead of wrapping elements in unnecessary div tags (which affect accessibility and CSS styling), use fragments (`<>...</>`) or utilize React's built-in `Fragment` component for cleaner markup without introducing extra elements.


1
2
3
4
5
6
7
8
9
// Using fragments
function FragmentExample() {
  return (
    <>
      <p>Paragraph 1</p>
      <p>Paragraph 2</p>
    </>
  );
}

4b: Organizing Components:

As your app expands, organizing components becomes crucial. A best practice is to have one component per file for better readability and maintainability. For larger projects, consider giving each component its own directory, including additional files like CSS modules or testing-related files.


5. Slow Initial Page Load:

Larger React applications can suffer from slow initial page loads due to the time it takes for the browser to download the JavaScript bundle. Code splitting techniques, such as dynamic imports and lazy loading with React's `Suspense` component, allow you to load code asynchronously and improve the user experience by reducing initial load times.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// Dynamic imports and lazy loading with Suspense
const AsyncComponent = React.lazy(() => import('./AsyncComponent'));

function App() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <AsyncComponent />
      </Suspense>
    </div>
  );
}

6. Prop Drilling:

Prop drilling occurs when a deeply nested component needs access to state that resides higher up in the component tree.

Avoid passing props through intermediate components that don't require them by utilizing state management libraries like Redux for global data or React's Context API for sharing data between parent and child components efficiently.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// Using React Context API
const MyContext = React.createContext();

function App() {
  const data = "Data from top-level component";

  return (
    <MyContext.Provider value={data}>
      <ParentComponent />
    </MyContext.Provider>
  );
}

function ChildComponent() {
  const data = useContext(MyContext);
  // Use 'data' here
}

7. Prop Plowing (Reducing Repetitive Code):

When dealing with multiple props passed down from a parent to a child component, repetitive code can clutter your codebase.

Using object spreading syntax (`{...props}`) allows you to pass all props simultaneously without explicitly naming each prop variable individually.


1
2
3
4
5
6
7
8
// Using object spreading syntax
function ChildComponent(props) {
  return (
    <div {...props}>
      {/* Child component content */}
    </div>
  );
}

8. Event Handlers in JSX:

Handling event functions within JSX often involves creating arrow functions every time an event occurs at multiple places throughout your codebase.

To make your code cleaner and more concise, utilize currying techniques by returning a function that handles custom arguments while accepting events as default parameters.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// Using currying
function App() {
  const handleCustomEvent = (customArg) => (event) => {
    // Handle event with 'customArg'
  };

  return (
    <div>
      <button onClick={handleCustomEvent("argumentValue1")}>Button 1</button>
      <button onClick={handleCustomEvent("argumentValue2")}>Button 2</button>
    </div>
  );
}

9: Storing State in a Single Object:

In some cases, developers may store all their application state within a single object when using React hooks' `useState`. While this approach might seem logical initially for organization purposes or performance gains (due to batched updates), it hinders flexibility if extraction into custom hooks is required later on.

1
2
3
4
5
6
7
// Avoid storing all state in a single object
function App() {
  const [count, setCount] = useState(0);
  const [text, setText] = useState("");

  // Use 'count' and 'text' independently
}

10: Extracting Logic into Custom Hooks:

Instead of relying solely on smart and dumb component patterns, consider extracting reusable logic into custom hooks. By structuring your components with multiple stateful values initially, you can easily

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// Custom hook for logic extraction
function useCustomLogic(initialValue) {
  const [value, setValue] = useState(initialValue);

  const increment = () => {
    // Logic to update 'value'
  };

  return { value, increment };
}

function App() {
  const { value, increment } = useCustomLogic(0);

  // Use 'value' and 'increment' in the component
}


In conclusion, mastering React involves not only understanding its core concepts but also recognizing and avoiding common anti-patterns. By breaking down large components, optimizing component nesting, and employing techniques like memoization and code splitting, you can create cleaner, more efficient React applications. Moreover, utilizing context and custom hooks, along with currying for event handling, will enhance code maintainability and reduce repetition. Remember, enhancing your React skills involves not only knowing what to do but also what not to do. By applying these tips and avoiding anti-patterns, you can write better React code and build more maintainable and performant applications. Happy coding!

No comments: