Refactoring tips: #01 š”
In this article, I am introducing a tool that fastens the process of breaking your code into pieces, saving them in another file, and finally importing them on your main application. At the end of this article, you will be able to make it all in one single step!
It is Sunday morning, during pandemics, watched my Squid Gameās episode and now I am going to do my fav hobby, code! I was coding a simple React App (Adopt Me) to sharpen my React skills this morning and found myself heading to the refactor commit. Such a pain, before I learned about a trick that now saves my timeā¦ a lot!
Letās say, you have your whole set of components in your App.js and things start to get crazy, so much that you need to split these components into another file and call back (as an imported file) in your main file until it is clean enough.
We all know the code is going to work, but it is always good to clean it and refactor it. So, let's go to my example and how I simplify this process.
Before cleaning the mess, the code seems something like this. There are two components I want to get rid of and save them in a different files.
My strategy to make it fast
1 āPick the piece you want to move to another file: Choose the chunk of code (usually a component that can be saved and imported in another file)
2 ā See that little light bulb š”? Yes, click on it. The magic lives there!
3āClick on āMove to a new fileā and see the magic š!
4ā Done! You have a new brand file called Pet.js (or whatever your function or components names are). No secrets here, you just did it.
5ā Import the file. No need, it has been done already.
This whole mechanism is done in TypeScript. TS is actually running in your code, even we donāt write it. Visual Code is constantly running TypeScript and making these changes for you. So use it in your favor.
Benefits: Now that we have Pets in a file and App in another file, it is easier to maintain, debug and share this file with another programmer, as things will be easier to see right the way.
In summary, this small tip has been very helpful to cut some precious time in code refactoring. I hope it is something new for someone. If you believe this can be improved or there are more efficient ways to automate refactoring, please let me know. I am always happy to see new things and learn more.
Cheers and keep coding!