Challenges of Implementing Shared Components between Next.js and React.js

Anshul Khatri
2 min readJun 2, 2023

Introduction

Implementing shared components between Next.js and React.js projects can be challenging due to the differences in their rendering and build configurations.

In this article, we will discuss the issues related to shared components and explore potential solutions.

  1. Routing Differences: Both React.js and Next.js have their own routing systems. React.js relies on external libraries like react-router-dom, which uses hooks like uselocation(). On the other hand, Next.js has its own built-in routing system and uses the useRouter() hook from 'next/router'. This difference in routing approaches can make it difficult to share components directly between the two frameworks.
  2. Styling Challenges: Styling files, such as SCSS or CSS, are handled differently in Next.js and React.js. Next.js uses CSS modules by default, where styles are scoped to the component, requiring a separate ‘component.module.css’ file. In contrast, React.js allows for global CSS declarations. This disparity in styling approaches can affect how shared components are structured and styled.
  3. Keying Components in Next.js: In React.js, adding keys to components is important, particularly when rendering lists of components. However, Next.js handles rendering and reconciliation differently, which may require a different approach to managing keys. Understanding and addressing this difference is crucial to ensure proper rendering of shared components in Next.js.

Finding Solutions

While direct sharing of components between Next.js and React.js may pose challenges, there are ways to overcome these limitations:

a. Shared Component Library: Create a separate shared component library that houses components common to both Next.js and React.js projects. This library can be independently maintained and versioned, allowing teams to easily reuse and update shared components.

b. Using a Package Management Tool: Consider using a package management tool like Lerna, which facilitates managing multiple packages within a single repository. Lerna enables you to create separate packages for Next.js and React.js, allowing you to share components and manage their dependencies efficiently.

Conclusion

Implementing shared components between Next.js and React.js projects requires careful consideration of the differences in their routing, styling, and rendering approaches. While challenges exist, solutions like creating a shared component library or using package management tools can help overcome these hurdles. By leveraging the right approach, you can achieve code reuse and maintainable shared components across both frameworks.

--

--