https://levelup.gitconnected.com/top-3-react-tricks-pros-like-to-use-to-reduce-the-size-of-component-980900370505

Don’t let your React component become a Frankenstein

Content

Intro

It always starts with something small, then you get excited and it grows to something big and later you lose control. And we talk about react components here. It was the major issue when I started to learn React, how to avoid the component to be exploded 🤯 with a bunch of features, JSX, and configuration. In this article, we will take an example of one of the UI components — the table component, and try to optimize it using 3 tricks that will let us scale like a Pro 😎.

The table component will have a few features, that can be later extended:

Our application will look like this:

And initially, the table component will look like this, and later we are going to optimize it:

1. The power of Namespaces

It is very common for React components to grow the number of types (interfaces, enums) and constants. The First technique we can use is namespaces. It is our config file that can store our constants, types, and even pure helper functions, as it’s not necessary to keep it inside the component. Let’s take a look at it closer:

Then we can update our table component props type:

2. Splitting to sub-components and sharing the state

At this point, we know where we can move our types, constants, and helper functions. Next, we will figure out what to do with sub-components. The small child components that we split our major big components. There 2 things to consider:

  1. Always create your child's components outside the body of the main component: either in the same file or in other files. Otherwise, it will raise the issue with performance, and child components will create each time the state is updated.