React Interview Questions: Tree Shaking for Smaller Bundles

⚛️ Top 150 React Interview Questions – 116/150 📌 Topic: Tree Shaking ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHAT is it? Tree Shaking is a term used in JavaScript for dead-code elimination. It relies on the static structure of ES6 module syntax (import / export) to remove unused code during the build process. Only the code that is actually imported and used remains in the final production bundle. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHY use it? 📦 Smaller Bundle Size Removes functions or components that are exported but never used ⚡ Performance Faster download time and quicker execution 🧹 Clean Production Build Keeps final .js files lean and optimized ━━━━━━━━━━━━━━━━━━━━━━ 🔹 HOW to do it? ✅ Step 1: Use Named Exports (math.js) export const add = (a, b) => a + b; export const sub = (a, b) => a - b; ✅ Step 2: Import Only What You Need (app.js) import { add } from './math'; console.log(add(10, 5)); 👉 Result: The sub function is removed from the final production bundle. ⚠️ Important: Tree Shaking works only with ES Modules (import/export) not with CommonJS (require/module.exports). ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHERE to use it? 🛠️ Utility Libraries Import specific functions from libraries like lodash-es or date-fns 🎨 Component Libraries Import individual icons/components from large libraries like lucide-react 🚀 Production Builds Always build with: npm run build Bundlers like Webpack, Rollup, and Vite automatically apply Tree Shaking. ━━━━━━━━━━━━━━━━━━━━━━ 📝 SUMMARY (Easy to Remember) Think of a Live Tree 🌳 When you shake it, the dead leaves (unused code) fall off. Only the strong branches (used code) remain. That is Tree Shaking. ━━━━━━━━━━━━━━━━━━━━━━ 👇 Comment “React” if this series is helping you 🔁 Share with someone preparing for React interviews #ReactJS #TreeShaking #WebPerformance #FrontendDevelopment #BundleOptimization #Top150ReactQuestions #LearningInPublic #Developers ━━━━━━━━━━━━━━━━━━━━━━

  • No alternative text description for this image

Tree Shaking only removes unused exports with ES Modules, CommonJS bundles remain fully intact.

Like
Reply

To view or add a comment, sign in

Explore content categories