So, youâve been writing React for a while, and now your project looks like it was built during a caffeine-fueled all-nighter. (Spoiler: it probably was). Donât worry, weâve all been thereâstate everywhere, props drilling like an oil rig, and components that could double as Tolstoy novels. Itâs time to refactor. Letâs make your code less âGen Z meme dumpâ and more âclean aesthetic Notion board.â
1. The Monster Component đ
Before (aka: why does this file have 500 lines??):
function ProfilePage({ user }) {
return (
<div>
<h1>{user.name}</h1>
<img src={user.avatar} alt="profile" />
<p>{user.bio}</p>
<button onClick={() => alert("Friend request sent!")}>
Add Friend
</button>
</div>
);
}
Looks fine until you realize youâre adding feature after feature and now this component is basically your entire app.
After (aka: therapy & boundaries):
function ProfilePage({ user }) {
return (
<div>
<UserHeader user={user} />
<UserBio bio={user.bio} />
<AddFriendButton />
</div>
);
}
function UserHeader({ user }) {
return (
<>
<h1>{user.name}</h1>
<img src={user.avatar} alt="profile" />
</>
);
}
function UserBio({ bio }) {
return <p>{bio}</p>;
}
function AddFriendButton() {
return (
<button onClick={() => alert("Friend request sent!")}>
Add Friend
</button>
);
}
Breaking things down = fewer tears later. Also, now you can actually find stuff in your file instead of scrolling like youâre on TikTok.
2. Props Drilling: The Emotional Damage Version đ
Before (youâre basically Amazon delivering props across 12 components):
function App() {
const user = { name: "Alex" };
return <Layout user={user} />;
}
function Layout({ user }) {
return <Sidebar user={user} />;
}
function Sidebar({ user }) {
return <UserProfile user={user} />;
}
function UserProfile({ user }) {
return <p>{user.name}</p>;
}
After (Context API aka âtherapy sessionâ):
const UserContext = React.createContext();
function App() {
const user = { name: "Alex" };
return (
<UserContext.Provider value={user}>
<Layout />
</UserContext.Provider>
);
}
function Layout() {
return <Sidebar />;
}
function Sidebar() {
return <UserProfile />;
}
function UserProfile() {
const user = React.useContext(UserContext);
return <p>{user.name}</p>;
}
Boom. No more prop-passing Olympics. đ
3. State Chaos đľâđŤ
Before (state scattered like your thoughts at 3 AM):
function Counter() {
const [count, setCount] = React.useState(0);
const [theme, setTheme] = React.useState("light");
const [username, setUsername] = React.useState("");
return (
<div className={theme}>
<h1>{username || "Guest"}</h1>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>+</button>
</div>
);
}
After (useReducer, aka âorganize your chaosâ):
function Counter() {
const initialState = { count: 0, theme: "light", username: "" };
function reducer(state, action) {
switch (action.type) {
case "increment":
return { ...state, count: state.count + 1 };
case "setTheme":
return { ...state, theme: action.value };
case "setUser":
return { ...state, username: action.value };
default:
return state;
}
}
const [state, dispatch] = React.useReducer(reducer, initialState);
return (
<div className={state.theme}>
<h1>{state.username || "Guest"}</h1>
<p>{state.count}</p>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
</div>
);
}
Cleaner, scalable, and doesnât feel like juggling flaming swords. đĽ
đŠ Refactor Red Flags: Signs Your React Code is Screaming for Help
- Your component scrolls longer than your Instagram feed.
If you need a scroll bar just to read the JSX, congratsâyouâve built a novella, not a component. Break it up. - Youâre passing props like youâre Santa Claus handing out presents.
If a prop has to go through more than 3 components to reach its destination, thatâs not âdata flow,â thatâs emotional trauma. Time for Context or state management. - Your function names look like bad clickbait.
Example:handleButtonClickWhenUserIsLoggedInAndHasNotifications
. No one wants to read that. Chop it down or extract logic into smaller functions. - You have more
useState
calls than brain cells after finals week.
If your state section looks like a shopping list, switch touseReducer
or context before you lose your mind. - Console.log() is basically your debugger.
If youâve got 17console.log
s sprinkled everywhere just to figure out whatâs happeningâyeah⌠refactor and get proper debugging or dev tools. - Your CSS is basically a horror story.
Inline styles everywhere, classNames longer than CVS receiptsâmaybe itâs time to refactor into styled components, Tailwind, or at least organize things. - The file name is
utils.js
and it has 900 lines.
Letâs be real: that file is a dumpster fire. Break it down before future you files a restraining order. - Half your components are named
SomethingWrapper
.
âWrapperâ is dev code for âI gave up.â If youâve got wrappers wrapping wrappers⌠time to refactor.
đĽ Pro tip: If your future self opens the file and immediately regrets past-life decisions, thatâs your sign. Refactor.
Prompt Examples: How to Think About Refactoring
Sometimes you just need to ask yourself the right question before diving into code chaos. Try these prompts when staring at your codebase in despair:
- âIf I left this code for 6 months, would I understand whatâs going on when I come back?â
- âDoes this component do one thing, or is it secretly three apps in a trench coat?â
- âAm I passing props through components that donât even use them?â
- âWould future me send past me a hate letter for this function name?â
- âIs my state management system a strategy or just vibes?â
- âCould someone new to the project figure this out without crying?â
Final Thoughts â¨
Refactoring React code is like cleaning your room: you donât want to, but youâll feel less like a swamp goblin when itâs done. Break components down, stop drilling props like a construction worker, and wrangle your state before it wrangles you.
Your code (and your sanity) will thank you. đ