How to keep React components small (2024)

How to keep React components small (3)

As a rule of thumb for our team at Finnovate.io, if a React component has more than 200 lines of code, then it is too big. Big components are difficult to read, difficult to maintain and nearly impossible to unit test. Fortunately, it is not so hard to abstract code away from components with a few pointers.

When refactoring a large component, one of the first things I would look for are business logic and functions that are not directly tied to the component state. For example, if you have a helper function in your component that looks like this:

function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}

There is no reason to keep that function in the component itself. We can simply move this function into a separate file:

export function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}

And import the function into the component:

import { capitalizeFirstLetter } from './stringlib';

Now the function and the business logic within it can be unit tested independently and reused by multiple components. If possible, keep functions pure they are deterministic and very easy to unit test.

React hooks allow developers to do something that wasn’t possible before its introduction — they allow for the abstraction of code that is coupled with component state. For example, if the code in your component looks like this:

const [ customers, setCustomers ] = useState([]);
const [ isLoading, setIsLoading ] = useState(false);
const [ errMessage, setErrMessage ] = useState('');
useEffect(() => {
setIsLoading(true);
// Calls API to get list of customers
getCustomers().then((response) => {
setCustomers(response.data.customers);
setIsLoading(false);
setErrMessage('');
}).catch((e) => {
setErrMessage(e.message);
setIsLoading(false);
});
}, []);

Much of this code can be moved into a custom hook:

export function useCustomers() {
const [ customers, setCustomers ] = useState([]);
const [ isLoading, setIsLoading ] = useState(false);
const [ errMessage, setErrMessage ] = useState('');
useEffect(() => {
setIsLoading(true);
// Calls API to get list of customers
getCustomers().then((response) => {
setCustomers(response.data.customers);
setIsLoading(false);
setErrMessage('');
}).catch((e) => {
setErrMessage(e.message);
setIsLoading(false);
});
}, []);
return [ customers, isLoading, errMessage ];
}

The component would simply imported into your component, just like a regular function:

import { useCustomers } from './customerHooks';...const [ customers, isLoading, errMessage ] = useCustomers();

Some additional points about custom hooks:

  • It is perfectly acceptable to have multiple layers of custom hooks to organize complex business logic
  • Custom hooks can be used by multiple components
  • Custom hooks can be unit tested independently with the React testing library

Finally, if your component is returning a large chunk of JSX, then it is an indication that you should break the component down into smaller components. This:

return (
<div>
... // a whole bunch of code
{
customers.map((customer) => (
<div>
... // a whole bunch of code
</div>
))
}
</div>
);

could be trimmed down to this:

return (
<div>
... // a whole bunch of code
{
customers.map((customer) => (
<CustomerCard customer={customer} />
))
}
</div>
);

The child component would in turn have its own CSS, imported functions and custom hooks. A child component can also have its own child components and so on. Similar to hooks and functions, components that are small and logically structured can be more easily unit tested.

The React.js framework gives us a lot of tools to keep files small and unit-testable. Take advantage of that!

Finnovate.io is a technology company focused on helping organizations build unique digital experiences on web, mobile and blockchain. Finnovate.io offers development services, training, consulting, as well as a platform that rapidly turns paper based content into digital interactive experiences.

How to keep React components small (2024)
Top Articles
13 Real Estate Thank-you Notes That Create Clients for Life (+ Templates)
What are the odds? They share a name, birthday, Eagle board date
Is Paige Vanzant Related To Ronnie Van Zant
Belle Meade Barbershop | Uncle Classic Barbershop | Nashville Barbers
Emmalangevin Fanhouse Leak
Espn Expert Picks Week 2
Does Publix Have Sephora Gift Cards
TS-Optics ToupTek Color Astro Camera 2600CP Sony IMX571 Sensor D=28.3 mm-TS2600CP
Chastity Brainwash
Jinx Chapter 24: Release Date, Spoilers & Where To Read - OtakuKart
Dumb Money, la recensione: Paul Dano e quel film biografico sul caso GameStop
Directions To Advance Auto
Moving Sales Craigslist
Dallas Craigslist Org Dallas
Dover Nh Power Outage
The Blind Showtimes Near Amc Merchants Crossing 16
Keci News
Plaza Bonita Sycuan Bus Schedule
Rs3 Ushabti
Weve Got You Surrounded Meme
Busted Mugshots Paducah Ky
manhattan cars & trucks - by owner - craigslist
Craigslist Efficiency For Rent Hialeah
Taylored Services Hardeeville Sc
Jail Roster Independence Ks
Noaa Marine Forecast Florida By Zone
Planned re-opening of Interchange welcomed - but questions still remain
Duke Energy Anderson Operations Center
Rund um die SIM-Karte | ALDI TALK
Melissa N. Comics
Palmadise Rv Lot
Rust Belt Revival Auctions
Mgm Virtual Roster Login
Rise Meadville Reviews
Drabcoplex Fishing Lure
Xemu Vs Cxbx
Agematch Com Member Login
Synchrony Manage Account
Usf Football Wiki
Michael Jordan: A timeline of the NBA legend
B.C. lightkeepers' jobs in jeopardy as coast guard plans to automate 2 stations
Wunderground Orlando
SF bay area cars & trucks "chevrolet 50" - craigslist
Weather In Allentown-Bethlehem-Easton Metropolitan Area 10 Days
The power of the NFL, its data, and the shift to CTV
Sofia Franklyn Leaks
Penny Paws San Antonio Photos
Uc Davis Tech Management Minor
Yourcuteelena
News & Events | Pi Recordings
Bedbathandbeyond Flemington Nj
91 East Freeway Accident Today 2022
Latest Posts
Article information

Author: Virgilio Hermann JD

Last Updated:

Views: 5830

Rating: 4 / 5 (41 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Virgilio Hermann JD

Birthday: 1997-12-21

Address: 6946 Schoen Cove, Sipesshire, MO 55944

Phone: +3763365785260

Job: Accounting Engineer

Hobby: Web surfing, Rafting, Dowsing, Stand-up comedy, Ghost hunting, Swimming, Amateur radio

Introduction: My name is Virgilio Hermann JD, I am a fine, gifted, beautiful, encouraging, kind, talented, zealous person who loves writing and wants to share my knowledge and understanding with you.