| How to Design Reusable React Components :👈 | 👉:How to Avoid Prop Drilling |
How to Refactor a Large React Component |
How to Refactor a Large React Component
1. Introduction
As a React application grows, some components become very large and difficult to maintain. A single component may contain UI rendering, API calls, state management, event handlers, validation, business logic, and conditional rendering.
This makes the component difficult to understand, test, debug, and modify.
Refactoring a large React component means restructuring its code into smaller, well-organized components, custom Hooks, utility functions, and services without changing its existing functionality.
The main objective is not simply to reduce the number of lines of code. It is to give each part of the application a clear responsibility.
2. Signs That a React Component Needs Refactoring
Consider refactoring when you notice the following problems:
- Too many responsibilities: The component handles API calls, validation, business logic, and UI rendering.
- Large JSX: The return statement contains deeply nested conditional rendering and complex markup.
- Repeated logic: Similar calculations or event-handling logic appears multiple times.
- Too many state variables: Managing multiple unrelated states becomes difficult.
- Complex useEffect: One effect performs several unrelated operations.
- Difficult testing: Testing one feature requires understanding the entire component.
- Frequent bugs: Small changes unexpectedly affect unrelated functionality.
- Long event handlers: Event handlers contain too much business logic.
There is no fixed line-count threshold for refactoring. A component with 300 lines may be manageable, while a component with 100 lines may already have too many responsibilities.
3. Example of a Large React Component
Consider an e-commerce component that performs several responsibilities:
- Fetches products from an API.
- Manages loading and error states.
- Searches products.
- Filters products by category.
- Adds products to the cart.
- Displays product information.
Before refactoring:
import { useEffect, useState } from "react";
function ProductPage() {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [search, setSearch] = useState("");
const [category, setCategory] = useState("all");
const [cart, setCart] = useState([]);
useEffect(() => {
async function fetchProducts() {
try {
const response = await fetch("/api/products");
if (!response.ok) {
throw new Error("Failed to fetch products");
}
const data = await response.json();
setProducts(data);
}
catch (err) {
setError(err.message);
}
finally {
setLoading(false);
}
}
fetchProducts();
}, []);
const filteredProducts = products.filter(product => {
const matchesSearch = product.name
.toLowerCase()
.includes(search.toLowerCase());
const matchesCategory =
category === "all" ||
product.category === category;
return matchesSearch && matchesCategory;
});
function addToCart(product) {
setCart(previousCart => [
...previousCart,
product
]);
}
if (loading) {
return <p>Loading products...</p>;
}
if (error) {
return <p>Error: {error}</p>;
}
return (
<div>
<h2>Products</h2>
<input
value={search}
onChange={e => setSearch(e.target.value)}
placeholder="Search products"
/>
<select
value={category}
onChange={e => setCategory(e.target.value)}
>
<option value="all">All</option>
<option value="electronics">Electronics</option>
<option value="clothing">Clothing</option>
</select>
<p>Cart Items: {cart.length}</p>
<div>
{filteredProducts.map(product => (
<div key={product.id}>
<h3>{product.name}</h3>
<p>{product.price}</p>
<button
onClick={() => addToCart(product)}
>
Add to Cart
</button>
</div>
))}
</div>
</div>
);
}
export default ProductPage;
This component works, but it combines several responsibilities. As more features are added, maintaining it becomes difficult.
4. Step-by-Step Refactoring Approach
Step 1: Identify Different Responsibilities
First, identify what the component is doing.
In our example:
| Responsibility | Suggested Location |
|---|---|
| Fetch products | Custom Hook or API service |
| Search and filter | Utility function or Hook |
| Cart management | Cart Hook or state management layer |
| Search input | ProductSearch component |
| Category selection | ProductFilter component |
| Product display | ProductList and ProductCard components |
| Page coordination | ProductPage component |
Step 2: Extract API Communication into a Service
API communication should not be unnecessarily mixed with UI rendering.
Create a separate service file.
File: services/productService.js
export async function getProducts(signal) {
const response = await fetch("/api/products", {
signal
});
if (!response.ok) {
throw new Error("Failed to fetch products");
}
return response.json();
}
Now the API communication is separated from the component.
Benefits:
- API logic can be reused.
- Components become easier to read.
- API changes can be managed centrally.
- Service functions can be tested independently.
Step 3: Extract Data Fetching into a Custom Hook
Instead of managing API loading, error, and data states inside the page component, we can create a custom Hook.
File: hooks/useProducts.js
import { useEffect, useState } from "react";
import { getProducts } from "../services/productService";
export function useProducts() {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
const controller = new AbortController();
async function loadProducts() {
try {
setLoading(true);
setError("");
const data = await getProducts(
controller.signal
);
setProducts(data);
}
catch (err) {
if (err.name !== "AbortError") {
setError(err.message);
}
}
finally {
if (!controller.signal.aborted) {
setLoading(false);
}
}
}
loadProducts();
return () => {
controller.abort();
};
}, []);
return {
products,
loading,
error
};
}
Now the page component does not need to know the internal API-fetching implementation.
It simply uses the Hook:
const {
products,
loading,
error
} = useProducts();
Step 4: Extract Search and Filter Logic
Search and filtering logic can be separated from the main component.
File: utils/filterProducts.js
export function filterProducts(
products,
search,
category
) {
return products.filter(product => {
const matchesSearch = product.name
.toLowerCase()
.includes(search.toLowerCase());
const matchesCategory =
category === "all" ||
product.category === category;
return matchesSearch && matchesCategory;
});
}
Usage:
const filteredProducts = filterProducts(
products,
search,
category
);
This function contains ordinary JavaScript logic, so it does not need to be a React component or custom Hook.
Step 5: Extract the Search Component
Search input has its own responsibility and can be extracted into a reusable component.
File: components/ProductSearch.jsx
function ProductSearch({ value, onChange }) {
return (
<input
type="text"
value={value}
onChange={e => onChange(e.target.value)}
placeholder="Search products"
/>
);
}
export default ProductSearch;
The parent component owns the search state and passes the value and callback to the child.
Step 6: Extract the Category Filter Component
File: components/ProductFilter.jsx
function ProductFilter({ value, onChange }) {
return (
<select
value={value}
onChange={e => onChange(e.target.value)}
>
<option value="all">All</option>
<option value="electronics">Electronics</option>
<option value="clothing">Clothing</option>
</select>
);
}
export default ProductFilter;
Step 7: Extract ProductCard
Each product should be displayed using a separate component.
File: components/ProductCard.jsx
function ProductCard({ product, onAddToCart }) {
return (
<div>
<h3>{product.name}</h3>
<p>{product.price}</p>
<button
onClick={() => onAddToCart(product)}
>
Add to Cart
</button>
</div>
);
}
export default ProductCard;
Step 8: Extract ProductList
Instead of keeping the product mapping logic inside the page, create a separate list component.
File: components/ProductList.jsx
import ProductCard from "./ProductCard";
function ProductList({ products, onAddToCart }) {
if (products.length === 0) {
return <p>No products found.</p>;
}
return (
<div>
{products.map(product => (
<ProductCard
key={product.id}
product={product}
onAddToCart={onAddToCart}
/>
))}
</div>
);
}
export default ProductList;
5. Final Refactored ProductPage Component
After extracting the responsibilities, the main component becomes much smaller.
File: ProductPage.jsx
import { useState } from "react";
import { useProducts } from "./hooks/useProducts";
import { filterProducts } from "./utils/filterProducts";
import ProductSearch from "./components/ProductSearch";
import ProductFilter from "./components/ProductFilter";
import ProductList from "./components/ProductList";
function ProductPage() {
const {
products,
loading,
error
} = useProducts();
const [search, setSearch] = useState("");
const [category, setCategory] = useState("all");
const [cart, setCart] = useState([]);
const filteredProducts = filterProducts(
products,
search,
category
);
function addToCart(product) {
setCart(previousCart => [
...previousCart,
product
]);
}
if (loading) {
return <p>Loading products...</p>;
}
if (error) {
return <p>Error: {error}</p>;
}
return (
<div>
<h2>Products</h2>
<ProductSearch
value={search}
onChange={setSearch}
/>
<ProductFilter
value={category}
onChange={setCategory}
/>
<p>Cart Items: {cart.length}</p>
<ProductList
products={filteredProducts}
onAddToCart={addToCart}
/>
</div>
);
}
export default ProductPage;
Notice that the main component now coordinates the page instead of implementing every feature itself.
6. Recommended Folder Structure After Refactoring
src/
│
├── components/
│ ├── ProductSearch.jsx
│ ├── ProductFilter.jsx
│ ├── ProductCard.jsx
│ └── ProductList.jsx
│
├── hooks/
│ └── useProducts.js
│
├── services/
│ └── productService.js
│
├── utils/
│ └── filterProducts.js
│
├── pages/
│ └── ProductPage.jsx
│
└── App.jsx
Each folder has a clear responsibility:
- components: Reusable UI elements.
- hooks: Reusable React stateful logic.
- services: API communication.
- utils: Pure JavaScript helper functions.
- pages: Page-level components that coordinate features.
7. When Should You Extract a Custom Hook?
Extract a custom Hook when you want to reuse or isolate React logic involving state, effects, context, or other Hooks.
Examples:
useProducts()- Product fetching and state.useAuth()- Authentication-related React logic.useDebounce()- Debounced values.useForm()- Form state and validation.
Example:
function useCounter() {
const [count, setCount] = useState(0);
function increment() {
setCount(previous => previous + 1);
}
function decrement() {
setCount(previous => previous - 1);
}
return {
count,
increment,
decrement
};
}
A component can use this Hook without knowing how its internal state is managed.
8. When Should You Extract a Utility Function?
Extract a utility function when the logic is ordinary JavaScript and does not need React Hooks or component rendering.
Examples:
- Formatting dates.
- Calculating totals.
- Filtering records.
- Sorting data.
- Validating simple values.
Example:
export function calculateTotal(items) {
return items.reduce(
(total, item) => total + item.price,
0
);
}
Utility functions are generally easier to test because they can be tested independently of React.
9. When Should You Extract a Child Component?
Extract a child component when a section of JSX has its own meaningful responsibility or needs to be reused.
Examples:
- ProductCard.
- UserProfile.
- OrderSummary.
- SearchPanel.
- NavigationMenu.
- DataTable.
A useful guideline is to extract a section when it has a clear purpose, understandable inputs, and a manageable responsibility.
10. Refactoring vs Performance Optimization
These concepts are related, but they are not the same.
| Refactoring | Performance Optimization |
|---|---|
| Improves code structure. | Improves execution or rendering performance. |
| Separates responsibilities. | Reduces unnecessary work. |
| Improves maintainability. | Improves responsiveness and efficiency. |
| Extracts components and Hooks. | Uses memoization, virtualization, and other suitable techniques. |
Important: Splitting a component does not automatically improve performance. A component may still re-render when its state, context, or props change. Use React DevTools Profiler to identify actual performance problems before optimizing.
11. Common Refactoring Mistakes
- Extracting too many tiny components: This can make navigation and understanding harder.
- Passing too many props: A child component may become tightly coupled to its parent.
- Moving everything into custom Hooks: Only extract logic that benefits from reuse or separation.
- Changing functionality during refactoring: Preserve existing behavior unless a functional change is intentionally required.
- Ignoring state ownership: Keep state at the appropriate level for the components that need it.
- Creating unnecessary global state: Local state is often sufficient.
- Using useMemo and useCallback everywhere: Memoization should solve an identified problem, not be applied automatically.
- Not testing after each change: Verify behavior as responsibilities are extracted.
- Overcomplicating folder structures: Organize files according to the actual size and needs of the application.
12. Best Practices for Refactoring Large React Components
- Understand the existing component before making changes.
- Identify responsibilities and dependencies.
- Refactor one responsibility at a time.
- Extract reusable UI into child components.
- Extract shared React logic into custom Hooks.
- Move API communication into service functions where appropriate.
- Move pure calculations into utility functions.
- Keep state close to the components that need it.
- Use meaningful component and function names.
- Preserve existing functionality.
- Run tests after each meaningful change.
- Use React DevTools to investigate performance separately.
13. Interview Questions and Answers
Q1. What is refactoring in React?
Refactoring is the process of restructuring existing React code without changing its external behavior. It improves readability, maintainability, testability, and separation of responsibilities.
Q2. When should you refactor a large React component?
When a component handles multiple responsibilities, contains complex JSX, has repeated logic, becomes difficult to test, or is difficult to modify safely.
Q3. How do you break down a large React component?
Identify its responsibilities and extract UI sections into child components, React stateful logic into custom Hooks, ordinary JavaScript logic into utility functions, and API communication into service functions where appropriate.
Q4. What is the difference between a component and a custom Hook?
A component is responsible for rendering UI, while a custom Hook shares React logic such as state management, effects, and context access.
Q5. Should API calls be written inside React components?
They can be written inside components for simple cases. However, extracting API communication into service functions or using a data-fetching library can improve separation, reuse, and testability.
Q6. Does splitting a large component improve performance?
Not automatically. Component splitting primarily improves code organization. Performance improvements require identifying and addressing unnecessary rendering or expensive calculations.
Q7. How do you ensure refactoring does not break existing functionality?
Understand the existing behavior, add or maintain tests, make small changes, and verify the application after each meaningful refactoring step.
Q8. What is the single-responsibility principle in React?
It means that a component, Hook, or function should have one clear primary responsibility. This makes code easier to understand, maintain, and test.
Q9. Should all state be moved into custom Hooks?
No. Local state should remain in the component when it is simple and used only there. Extract stateful logic when it is reusable or when doing so makes the component significantly easier to understand.
Q10. What is the difference between refactoring and rewriting?
Refactoring improves the internal structure while preserving existing behavior. Rewriting replaces an implementation and may involve significant changes to its structure or functionality.
14. Final Takeaway
Refactoring a large React component is about separating responsibilities and making the code easier to understand, test, and maintain.
Remember the following:
- Extract UI into smaller components.
- Extract reusable React logic into custom Hooks.
- Move ordinary calculations into utility functions.
- Separate API communication where appropriate.
- Keep the main page component focused on coordinating the page.
- Preserve existing behavior and test after each change.
A well-refactored React component should have a clear responsibility, readable code, and simple dependencies.
| How to Design Reusable React Components :👈 | 👉:How to Avoid Prop Drilling |
Comments and Discussion