Home > Web Front-end > JS Tutorial > body text

Taming the Beast: How I Refactored a Messy React Component

WBOY
Release: 2024-08-19 17:13:33
Original
963 people have browsed it

Taming the Beast: How I Refactored a Messy React Component

We’ve all been there. You open up a React component that you wrote a few months ago, and it feels like you’re looking at code written by someone who was in a hurry — because you probably were. Deadlines were looming, and features needed to be shipped. Fast forward to today, and it’s time to refactor that messy component.

So, here’s how I tackled it.

The Initial Horror

The first thing I noticed was that the component had grown way too large. It was trying to do everything like handle state, make API calls, manage complex UI logic, and even apply styles directly. It was a single file of over 540 lines, and reading through it felt like wondering in a jungle without a map.

The first step was accepting the reality: This code was no longer maintainable. If I, the person who wrote it, could barely follow what was happening, someone else wouldn’t stand a chance. So, I decided to break it down.

Breaking It Down

I started by identifying the different responsibilities of the component. There were three clear areas:

  1. State Management: Handling the component’s state was intertwined with UI logic.

  2. API Calls: Fetching data and handling loading states.

  3. Rendering UI: Displaying the data in a somewhat complex UI structure.
    Each of these responsibilities needed to be separated.

Extracting Hooks for State and API Logic

The first thing I did was to extract the state management and API logic into custom hooks. This not only cleaned up the component but also made it easier to test and reuse the logic elsewhere.

Mentioning some code here (not the original one):

function useDataFetching(apiEndpoint) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function fetchData() {
      try {
        let response = await fetch(apiEndpoint);
        let result = await response.json();
        setData(result);
      } catch (err) {
        setError(err);
      } finally {
        setLoading(false);
      }
    }

    fetchData();
  }, [apiEndpoint]);

  return { data, loading, error };
}

Copy after login

With useDataFetching, I pulled out the API call logic and handled the loading and error states. Now, the component only needs to call this hook and get the necessary data, clean and simple.

Simplifying the UI Logic
Next, I looked at the rendering logic. Previously, I was checking for loading, errors, and data all within the render function, which made it quite hard to follow. I separated this logic into small, self-contained functions something like this (of course not the original one ;)

function renderLoading() {
  return <p>Loading...</p>;
}

function renderError(error) {
  return <p>Error: {error.message}</p>;
}

function renderData(data) {
  return <div>{/* Complex UI logic here */}</div>;
}
//After that, component is ni much pretty shape

function MyComponent() {
  const { data, loading, error } = useDataFetching('/api/data-endpoint');

  if (loading) return renderLoading();
  if (error) return renderError(error);
  if (data) return renderData(data);

  return null;
}
Copy after login

Final Talk

After breaking down the component, the file went from over 540 lines to just about 124, with logic that’s much easier to follow. The component now does one thing: render the UI. Everything else has been offloaded to custom hooks and utility functions.

This experience reinforced a few key lessons for me:

  • Don’t Fear Refactoring: It’s easy to leave messy code as it is, especially when it works. But taking the time to clean it up makes your life — and your future self’s life — so much easier.

  • Separation of Concerns: Keeping different concerns in different places (state, API, UI) made the code more modular, reusable, and testable.

  • Keep It Simple: Simplifying the render function by offloading logic to smaller functions made the component much more readable.

So, if you’ve got a messy component sitting around like you are, don’t hesitate to refactor. It’s not just about clean code — it’s about making your life easier as a developer. And who wouldn’t want that?

The above is the detailed content of Taming the Beast: How I Refactored a Messy React Component. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!