What is Tree-Shaking?
Tree-shaking is a dead code elimination technique used by modern JavaScript bundlers (Webpack, Rollup, Vite, etc.) to remove unused exports from your final bundle.With React Icons, importing 10 icons from a pack of 5,000+ icons will only include those 10 icons in your bundle, not the entire pack.
How It Works
React Icons uses ES6 named exports, which allow bundlers to determine exactly which icons are used:Behind the Scenes
When you import fromreact-icons/fa, the bundler:
- Analyzes which icons are actually used in your code
- Includes only those icon components in the bundle
- Excludes all unused icons from the final output
- Optimizes the included icons during minification
Bundle Size Impact
Here’s a comparison of bundle sizes:Actual sizes vary based on the specific icons and your bundler configuration. These are approximate gzipped sizes.
ES6 Import Pattern
React Icons v3+ uses ES6 named imports for optimal tree-shaking:- Recommended (v3+)
- Legacy (v2)
Package Configuration
React Icons is configured for optimal tree-shaking:sideEffects: false
The"sideEffects": false declaration tells bundlers that:
- No code in this package has side effects
- Unused exports can be safely removed
- Aggressive tree-shaking is safe
This configuration is already set in React Icons - you don’t need to configure anything!
Verifying Tree-Shaking
Using Webpack Bundle Analyzer
Install and configure webpack-bundle-analyzer:Using Rollup Plugin Visualizer
For Vite or Rollup projects:Manual Bundle Size Check
Common Tree-Shaking Issues
Issue 1: Large Bundle Size
If your bundle is unexpectedly large:Issue 2: Dynamic Icon Loading
Issue 3: Re-exporting Icons
Best Practices
1. Import Only What You Use
2. Group Imports by Pack
3. Use Explicit Icon Maps
For dynamic icon selection:4. Avoid Conditional Imports
5. Code Splitting for Large Icon Sets
For pages with many icons, use dynamic imports:Bundler Compatibility
React Icons works with all modern bundlers that support ES6 modules:Most modern bundlers enable tree-shaking automatically in production mode.
Measuring Impact
Before and After Example
Alternative: Per-Icon Imports
For specific build systems (Meteor, older Gatsby), use@react-icons/all-files:
Debugging Tree-Shaking
Enable Webpack Stats
Check Bundle Contents
Performance Tips
- Use production builds: Tree-shaking is most effective in production mode
- Enable minification: Minifiers remove dead code after tree-shaking
- Use code splitting: Split icon-heavy components into separate chunks
- Lazy load icon packs: Use dynamic imports for rarely-used icons
- Monitor bundle size: Use tools like Bundle Analyzer regularly
Icon Imports
Learn the import patterns that enable tree-shaking
TypeScript
See type-safe imports and tree-shaking