0PricingLogin
React Academy · Lesson

Peer Dependencies and Tree Shaking

Declare React as a peer dependency, enable side-effects-free tree shaking, and test the published package.

What Are Peer Dependencies?

Peer dependencies declare packages that your library requires but expects the consumer to provide. In your library's package.json, React belongs in peerDependencies, not dependencies. When a user installs your library, npm/yarn does not install React automatically — the user's app already has React, and your library shares that instance.

Why Not Put React in dependencies?

If React is in your library's dependencies, npm may install a second copy of React alongside the consumer's React. Two React instances in the same app break all hooks with the "Invalid hook call" error. By declaring React as a peerDependency, you tell npm "I need React, but use the one the consumer already has."

All lessons in this course

  1. Bundling with Rollup and tsup for Libraries
  2. ESM and CJS Dual Package Output
  3. Peer Dependencies and Tree Shaking
  4. Publishing to npm and Semantic Versioning
← Back to React Academy