How to optimize a React app
12 July 2022 (Updated 12 July 2022)
Use cra-bundle-analyzer to understand your bundle
Install cra-bundle-analyzer
which is a wrapper around webpack-bundle-analyzer
:
npm i -D cra-bundle-analyzer
Add NPM script:
{
"scripts": {
// other scripts...
"analyze-bundle": "cra-bundle-analyzer"
}
}
Run analyzer:
npm run analyze-bundle
This will generate and open a build/report.html
file that looks something like this:
Use the Search modules box to understand what files are increasing your bundle size.
Use code splitting / dynamic imports
Use React.lazy
to split your code into bundles that are dynamically loaded only when they’re needed. If you’re using React Router, route-based code-splitting might be a good option.
Remove unused packages
Go through your package.json
file and remove any packages that your app doesn’t use. For example, if you suspect lodash
isn’t being used, do a search in your IDE / code editor for the string from 'lodash
.
Other notes
- These are only a few optimization techniques. There’s probably a ton more I need to look into.
- Optimize lodash imports
Tagged:
React tooling
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment