Code splitting is one of the best thing on every programming aspect that you use. It is the process of breaking a larger number of codes into smaller blocks.
Code spliting can always be useful , It is
--> easy to abstract
--> easy to debug
--> easy to unit test
--> easy to reuse and avoid duplication of code
If you're using of NextJs you might be aware of it's one of the advantage that nextjs provides code-splitting out the box.
So is this not possible in react? Definitely possible why not? with a minimal modification we can achieve the thing provided in nextjs in react too.
works fine ok now I need to check the given value as email or not in other place of the application! What will you do ?
works fine no issues ! but wait is this a standard way to do same code is written in two places if that looks ok for you , but your code reviewer will catch you how we can reuse this ?
isEmail is the common function that holds all the logic for checking a given value in email or not .
this is great now you can reuse this logic anywhere and your code reviewer fill make a ✅ for your code
This is a common behaviour and this how many of us use what's new here ? ? ok if your using like above that's fine keep doing along with the following , else do both
let me explain the things with the a bot that i've made for the HR's . This app generates reply messages for the hr that is generates using some of the commonly used keywords .
generateReplyMessage is the common helper function that can be used to generate messages.
This is how we use that function
so seems normal like the previous one ! chill here comes the intresting part .
believe it or not a greater MNC rejected me offer by telling Code Splitting as a reason!! even though I did some but not fully 😢
not because of that it can be a life saver when your application size increases by a large amount.
Have you ever had a question when will the imported files will be called?
--> option A : During the imported function/Component execution
--> option B : Before parent component render
if your answer is A then make a console and check you'll get it . Even before the parent render the import statements are loaded !
Oh oh !! then how can I load the files only when it needs ??
React provides a better and easy way to achieve this.You can achieve this by just modifying the import like
by doing so the
generateReplyMessage will be imported from the
helper functions only during the call of
generateReplyMessage uhhh this is how it should execute. By this method we can achieve the Code-Splitting in react.
Wait how it will be evidenced in browser ?
with code splitting
you can see two chunk files are loaded second one is loaded only when the
generateReplyMessage is called.
this will have a single chunk as a whole
this shows some splitting process has been done .That's it !
Check this offical docs
Get the code here
Thanks for your time
Happy coding ! Keep Sharing