This content originally appeared on DEV Community and was authored by Muhammad Hasnat
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:
State Management: Handling the component’s state was intertwined with UI logic.
API Calls: Fetching data and handling loading states.
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 };
}
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;
}
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?
This content originally appeared on DEV Community and was authored by Muhammad Hasnat
Muhammad Hasnat | Sciencx (2024-08-18T18:06:35+00:00) Taming the Beast: How I Refactored a Messy React Component. Retrieved from https://www.scien.cx/2024/08/18/taming-the-beast-how-i-refactored-a-messy-react-component/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.