How to Build a Custom SVG Icon Library in React and Next.js
Build a reusable React icon library with SVGO and SVGR, tested in four bundlers. Five icons cost 445 bytes gzipped, or 41 KB when the package is built wrong.
On this page
- Do you need your own library?
- Package layout
- Step 1: clean the files with SVGO
- Step 2: generate components with SVGR
- Step 3: write the base component
- Step 4: set up the package
- What tree shaking really costs
- Barrel, name map, lazy loading or sprite
- Next.js App Router
- Managing icon updates in a monorepo
- Config bugs we hit
- What we did not test
To build a custom SVG icon library in React, clean your SVG files with SVGO, turn them into components with SVGR, and publish plain ES modules, one file per icon, with "sideEffects": false in package.json. Built that way, five icons from a 1,000-icon package cost 445 bytes gzipped in our Vite test. Built with forwardRef in one bundled file, the same five icons cost 41 KB, even with sideEffects: false set.
We built this library from real SVGs and ran every snippet below on 2026-11-05: Lucide's 2,317 files as source (lucide-static 1.69.0, ISC license), SVGO 4.1.0, SVGR 8.1.0, TypeScript 7.0.2, React 19.3.1, and Next.js 16.4.5. Bundle tests ran in esbuild 0.28.2, Rollup 4.67.5, webpack 5.112.2 and Vite 8.3.6.
Quick answer
- Pipeline: SVGO 4 first, then SVGR with its own SVGO switched off, then plain tsc. A 1,000-icon rebuild took about 3.4 seconds.
- Best output: one file per icon, plain function components, sideEffects false. Five icons cost 341 to 529 bytes gzipped in all four bundlers.
- The trap: forwardRef in a single bundled file pulled in all 1,000 icons, 41 to 70 KB gzipped, with sideEffects false set.
- Dynamic names: an import-star wrapper ships the whole library. A small map of the icons you use stays near 500 bytes.
- Sprites: not smaller than components by themselves. A full 200-icon sprite was 15 percent larger than all 200 components.
- Monorepo: the barrel made 1,013 requests in Vite dev. One optimizeDeps line cut that to 11.
Do you need your own library?
Build one when you have icons nobody else ships: brand marks, product symbols, a designer's custom set. If you only need common interface icons, install an existing set such as Lucide and skip all of this. For a single file, the SVG to component converter is faster, and React SVG icons covers the everyday ways to use them.
A reusable icon component in React needs four things: it scales with font size, takes its color from CSS, has correct types, and costs nothing when unused. The rest of this guide gets you there.
Package layout
packages/icons/
assets/icons/ source SVGs, committed
.clean/ SVGO output, ignored by git
src/icons/ SVGR output, generated
src/IconBase.tsx
src/index.ts
scripts/icon-template.cjs
scripts/index-template.cjs
scripts/check-icons.mjs
svgo.config.mjs
svgr.config.cjsName source files in kebab case. Our naming guide explains why a consistent scheme matters, and the clash test below shows what happens without one.
Step 1: clean the files with SVGO
Run SVGO yourself, before SVGR. SVGR 8.1.0 pins SVGO 3.3.5 inside its plugin, and standalone SVGO 4 has safer defaults. SVGR's last release is from 2023-08-15, though its repo was last pushed on 2026-03-01 and it worked with everything we tested.
// svgo.config.mjs
export default {
plugins: [
'preset-default',
'removeDimensions',
'removeXMLNS',
{ name: 'removeAttrs', params: { attrs: 'class' } },
],
};On 200 icons this took 95,163 bytes to 54,459, which is 43 percent smaller. That includes a license comment and pretty-printing in Lucide's files, so yours may shrink less. Keep license notices elsewhere if your source license asks for them. The SVG optimizer lets you check one file by eye.
If your source files have fixed colors, SVGO can swap them for currentColor: override preset-default with convertColors: { currentColor: true }. Only do this for single-color sets. On a test icon with one dark and one red path, it turned both into currentColor and merged them, so the second color was gone.
Did the cleaning change anything visible? We rendered 200 icons at 48 px in Chrome 156 and compared pixels. Of 649,792 pixels, 5,196 changed across 155 icons, and only 10 changed by more than 96 out of 255. The worst icon we opened had its separate paths merged into one, which alters anti-aliasing where strokes cross. We could not see the difference by eye. Components and sprite then matched the cleaned files exactly, with 0 pixels different.
Step 2: generate components with SVGR
// svgr.config.cjs
module.exports = {
typescript: true,
jsxRuntime: 'automatic',
svgo: false,
template: require('./scripts/icon-template.cjs'),
indexTemplate: require('./scripts/index-template.cjs'),
};The template makes each icon render a shared IconBase, so size and accessibility rules live in one file.
// scripts/icon-template.cjs
module.exports = ({ componentName, jsx, exports }, { tpl }) => {
jsx.openingElement.name.name = 'IconBase';
jsx.closingElement.name.name = 'IconBase';
// SVGR only adds {...props} to an element named svg, so add it back.
jsx.openingElement.attributes.push({
type: 'JSXSpreadAttribute',
argument: { type: 'Identifier', name: 'props' },
});
return tpl`
import { IconBase, type IconProps } from '../IconBase.js';
const ${componentName} = (props: IconProps) => ${jsx};
${exports};
`;
};You also need a custom index. SVGR's default leaves off file extensions, and inside a "type": "module" package that failed in webpack ("Can't resolve './Check'", "fully specified") and in plain Node (ERR_MODULE_NOT_FOUND). esbuild, Rollup and Vite accepted it, so this bug can hide until a webpack user installs your package.
// scripts/index-template.cjs
const path = require('node:path');
module.exports = (files) =>
files
.map((file) => {
const name = path.basename(file.path, path.extname(file.path));
return `export { default as ${name} } from './${name}.js';`;
})
.join('\n') + '\n';The last script guards against a bug SVGR will not tell you about. When two SVGs map to one component name, it overwrites the file and exits 0. Running it on all 2,317 Lucide files produced 2,303 components on Linux, with no warning. Five more pairs differ only by case (letter-s and letters), so they would collide on macOS or Windows: 19 lost icons in total.
// scripts/check-icons.mjs
import { readdirSync } from 'node:fs';
const svgs = readdirSync('.clean').filter((f) => f.endsWith('.svg'));
const made = readdirSync('src/icons').filter((f) => f.endsWith('.tsx'));
const names = new Set(made.map((f) => f.toLowerCase()));
if (names.size !== svgs.length) {
console.error(`${svgs.length} SVGs became ${names.size} components. Rename the clashing files.`);
process.exit(1);
}Step 3: write the base component
// src/IconBase.tsx
import type { SVGProps } from 'react';
export type IconProps = Omit<SVGProps<SVGSVGElement>, 'width' | 'height'> & {
/** Any CSS length or a number of pixels. Default: follows the font size. */
size?: number | string;
/** Set this when the icon carries meaning on its own. */
title?: string;
};
export function IconBase({ size = '1em', title, children, ...props }: IconProps) {
return (
<svg
width={size}
height={size}
aria-hidden={title ? undefined : true}
role={title ? 'img' : undefined}
focusable="false"
{...props}
>
{title ? <title>{title}</title> : null}
{children}
</svg>
);
}<Menu /> rendered with aria-hidden="true". <User title="Account" /> rendered with role="img" and a <title> element. A ref reached the SVG element in React 19 without forwardRef, because React 19 passes ref as a normal prop. An icon-only button still needs its own accessible name.
Step 4: set up the package
{
"name": "@acme/icons",
"version": "1.0.0",
"type": "module",
"sideEffects": false,
"files": ["dist"],
"exports": {
".": { "types": "./dist/index.d.ts", "default": "./dist/index.js" },
"./*": { "types": "./dist/icons/*.d.ts", "default": "./dist/icons/*.js" }
},
"scripts": {
"icons": "rm -rf .clean src/icons && svgo -f assets/icons -o .clean && svgr --out-dir src/icons .clean && node scripts/check-icons.mjs",
"build": "pnpm icons && tsc"
},
"peerDependencies": { "react": ">=19" }
}// src/index.ts
export * from './icons/index.js';
export type { IconProps } from './IconBase.js';Use tsconfig options target: es2022, module: esnext, moduleResolution: bundler, jsx: react-jsx, declaration: true, rootDir: src and outDir: dist. No bundler is involved, and that is on purpose: tsc keeps one output file per icon. Many tutorials reach for tsup, whose README now says it is not actively maintained and points to tsdown (checked 2026-11-05).
The rm -rf matters too. SVGR left a stale component in the output folder when we regenerated, so a deleted icon could survive in your package without it.
Types held up. <Menu size={20} title="Menu" ref={r} /> and the deep import @acme/icons/Check compiled under moduleResolution set to bundler and to nodenext. An unknown icon name and a width prop both failed as they should. publint reported "All good!" on the package. TypeScript 7 removed node10 resolution, so we could not test it.
What tree shaking really costs
This is the test no result we read had run. We built the same 1,000-icon library nine ways and imported five icons (Menu, Search, User, X, Check) in each bundler, with React external. Figures are gzipped bytes of minified output.
| Package build | esbuild | Rollup | webpack | Vite |
|---|---|---|---|---|
| Arrow, per file, false | 415 | 362 | 341 | 345 |
IconBase, per file, false | 529 | 460 | 443 | 445 |
forwardRef, per file, false | 483 | 410 | 381 | 395 |
| Arrow, per file, no field | 4,152 | 362 | 341 | 345 |
forwardRef, per file, no field | 72,060 | 47,794 | 41,942 | 41,353 |
| Arrow, single file, false | 4,057 | 375 | 341 | 345 |
forwardRef, single file, false | 69,904 | 47,825 | 41,945 | 41,351 |
forwardRef + PURE, single file, false | 6,804 | 423 | 404 | 391 |
| CommonJS, single file, false | 69,668 | fails | 63,852 | 64,352 |
"False" means "sideEffects": false in package.json. "No field" means it is absent. The Rollup failure comes from our setup, which had no CommonJS plugin.
The field lets a bundler drop whole modules you never import. In a single-file package there is only one module, and you did import it. Each const Icon = forwardRef(...) is then a top-level function call the bundler cannot prove safe to remove, so all 1,000 icons stayed. A /*#__PURE__*/ comment or separate files fix it. In our tests, plain arrow components shook out in Rollup, webpack and Vite even with no field.
The high esbuild numbers on arrow and PURE rows are partly a side effect of our test. With React external, esbuild kept one react/jsx-runtime import line per dropped module. With React bundled, the arrow package at 1,000 icons came to 1,099 bytes with the field and 3,138 without, of which 755 is React's JSX runtime. Set the field regardless.
Cost then grows with the icons you use, not the library's size. In Vite, the per-file package cost 445 bytes for 5 icons from either a 200-icon or a 1,000-icon library, 1,382 bytes for 20, 4,802 for 100 and 40,802 for all 1,000.
Barrel, name map, lazy loading or sprite
The same five icons, built in Vite from the IconBase package. Figures are total gzipped bytes needed to show them.
| Method | 200-icon library | 1,000-icon library |
|---|---|---|
| Named import from the barrel | 445 | 445 |
| Deep import per icon | 445 | 445 |
| Small typed map | 502 | 502 |
Lazy map, import() per icon | 6,014 | 17,670 |
import * with Icons[name] | 12,035 | 51,058 |
| Sprite of all icons, plus component | 10,816 | 47,222 |
| Sprite of only these 5, plus component | 464 | 464 |
Named imports are the default. The barrel costs no more than deep imports in a production build.
The name wrapper needs a limit. <Icon name="menu" /> is a nice API, but import * as Icons ships everything. Our earlier version of this article recommended exactly that pattern, and it was wrong. List the icons you use instead, and you also get a type error on a bad name:
import { Check, Menu, Search, type IconProps } from '@acme/icons';
const icons = { check: Check, menu: Menu, search: Search };
export type IconName = keyof typeof icons;
export function Icon({ name, ...props }: IconProps & { name: IconName }) {
const Glyph = icons[name];
return <Glyph {...props} />;
}Lazy maps are for names you cannot know at build time, such as icons chosen in a CMS. The map itself cost 4,594 bytes at 200 icons and 16,250 at 1,000, because it lists every chunk. Six more requests followed (five icons plus IconBase), and the build wrote 1,002 chunks.
Sprites do not win on bytes alone. All 200 icons came to 10,648 bytes gzipped as a sprite, against 9,254 as components. Their real case is that the file is cached apart from your JavaScript and works across frameworks. We did not measure runtime or parsing cost, and our font, sprite and inline test covers loading in more depth. The SVG sprite maker builds one from your files.
Next.js App Router
The package needed no transpilePackages setting. next build on Next 16.4.5 finished in about 7 seconds with the 1,000-icon package, importing five icons from the barrel:
| Page | Icons in client JS | SVGs in HTML |
|---|---|---|
| Server component | 0 | 5 |
'use client' component | 5 | 5 |
So icons in server components ship no icon JavaScript at all, though each one appeared twice in the page HTML: once as markup and once in the React data payload. optimizePackageImports was not needed for this production build, and removing sideEffects did not change the result for these arrow components. More on the framework side is in our Next.js SVG guide.
Managing icon updates in a monorepo
Keep one source folder and treat everything generated as disposable. We ran this as a pnpm 11 workspace, with apps depending on "@acme/icons": "workspace:*".
Build the package before the apps. Apps import from dist, so pnpm --filter @acme/icons build comes first. A 1,000-icon rebuild took 590 ms in SVGO, 2,340 ms in SVGR and 418 ms in tsc.
Fix the barrel in Vite dev. Vite does not pre-bundle linked packages (its docs confirm this), so the barrel loads every icon as a separate request:
| Five icons, Vite dev | Requests | Cold load |
|---|---|---|
| Barrel | 1,013 | 3,594 ms |
Barrel with optimizeDeps | 11 | 391 ms |
| Deep imports | 16 | 355 ms |
Request counts are exact. Load times are rough, from one local machine. The fix goes in the consuming app:
// vite.config.js
export default { optimizeDeps: { include: ['@acme/icons'] } };Check that generated code is current. Regeneration was deterministic: two runs gave the same hash. If you commit src/icons, this CI step fails when someone edits generated code by hand, or changes an SVG without regenerating. It caught our test edit:
cp -r src/icons .before && pnpm icons && diff -r .before src/iconsTreat a removed icon as a breaking change. When we deleted check.svg and rebuilt, the consumer failed type checking with TS2305: Module '"@acme/icons"' has no exported member 'Check'. That is the behavior you want, so run tsc across apps in CI, and bump the major version if you publish outside the repo.
Config bugs we hit
![]()
fill-current on stroke icons. Our earlier version put this class on every icon. CSS beats the fill="none" attribute, so outlines turn into solid shapes (middle row). Stroke icons already get their color from stroke="currentColor", so leave the class off.
A lost viewBox. A svgo.config.js holding only preset-default makes SVGR's SVGO 3 remove viewBox, while --icon still sets the size to 1em. The icon stays at its original size and clips (bottom row). Our route of running SVGO 4 first avoids this.
The old removeViewBox: false override. It is still needed under SVGR's SVGO 3. In SVGO 4 it prints a warning that the plugin is not part of preset-default, exits 0, and does nothing useful, because SVGO 4 keeps viewBox by default.
What we did not test
- React 18. Everything ran on React 19. On React 18,
refneedsforwardRef, so use one file per icon or the PURE comment. - Real app totals. React stayed external in the bundle tables, so they show icon cost, not page cost.
- Other icon styles. The bundle and pixel tests used Lucide's stroke icons only. Multicolor and fill-based sets may compress differently.
- Other systems. We ran on Linux. The macOS and Windows clashes are worked out by comparing lowercase names, not observed.
- Runtime speed. We measured bytes, requests and pixels, not rendering or hydration time. Dev timings came from one machine on a slow disk.
What is the best way to build a reusable icon component in React?
Does sideEffects false make an icon library tree-shakable?
Is a barrel file bad for an icon library?
Should I use SVG sprites instead of React components?
How do I build a scalable SVG icon system across several apps?
Do I still need forwardRef for icon components?
Related posts