It is quite common in a large project such as a cms you will suffer large components which can have around thousand lines of code. Those components are quite difficult to maintain and people tend to scare to change logics there. But to make the project healthier you will still need to refactor code some time.
What
What will you do with a few thousands lines of code react components? it is the main question I will write about today about my experience when I dealt with these monster in my development projects.
How
Investigate the components.
- Normally these large components are built through the time by many developers so it is not straight away to refactor the component into smaller ones. I usually start with understanding how many functionalities this component is performing.
Breakdown functionalities and categorize them
- To have a plan on where to start so it is good to have an overview of functionalities and how important those are. In a large component not all functionalities have the same priorities, such as keyboard navigation is often a bonus function.
- When you have a group of functionalities and you can list core functionalities then you can start working on a plan for refactoring.
Plan on refactoring
- It all depends on how much time you have for refactoring a component so you can have a appropriate plan. I usually see two approaches:
- keep the old implementation and start working on a new implementation and start using in a small place first.
- pick some functionalities or parts of the component to rewrite, extract.
Techniques
- HoC, High order component is very useful when you have a component that serves different logics with the same base. Then you can think of creating different components with the same base shared by HoC instead of adding everything in a large component.
- ReactContext, Context is an useful way to cut down props drilling and organizing states in a central place.
- Hooks, Hooks can be used to implement same functionalities cross functions.
- Layout, base components help you to scaffold your components.