Simplify code sharing and project structure with NX for React developers.

NX (https://nx.dev)is an open-source toolkit developed by Nrwl that helps you build and manage monorepos efficiently. It supports multiple frameworks like React, Angular, Node.js, NestJS, Next.js, and more.

Benefits of NX:

  • Code sharing between apps and libraries.
  • Optimized builds and tests using the affected feature (only rebuild/test what changed).
  • Clear dependency management between modules.
  • Easy CI/CD integration.
  • Rich plugin ecosystem.

Setting Up NX with React

We’ll create:

  • A React app: my-app
  • A shared UI library: ui
  • A reusable component: Button

1. Create a new NX workspace

npx create-nx-workspace@latest my-nx-react-app

Choose:

  • "apps with React"
  • App name: my-app
  • Layout: Integrated

2. Serve the React app

cd my-nx-react-app
nx serve my-app

Visit: http://localhost:4200

3. Generate a shared UI library

nx generate @nx/react:library ui

This creates a library in libs/ui.

4. Add a reusable Button component

nx generate @nx/react:component button --project=ui

This creates libs/ui/src/lib/button/button.tsx.
Edit it to look like this:


// libs/ui/src/lib/button/button.tsx
export function Button() {
  return <button style={{ padding: '10px 20px' }}>Click Me</button>;
}

5. Use the Button in your app

Edit apps/my-app/src/app/app.tsx:

import { Button } from '@my-nx-react-app/ui';

export function App() {
  return (
    <div>
      <h1>Hello from NX + React!</h1>
      <Button />
    </div>
  );
}

Done!

You now have a working React app using NX Monorepo, with a shared UI library and a reusable component with following structure

my-nx-react-app/
├── apps/
│   └── my-app/
│       └── src/
│           └── app/
│               └── app.tsx
├── libs/
│   └── ui/
│       └── src/
│           └── lib/
│               └── button.tsx
├── nx.json
├── project.json
├── package.json
└── README.md
  • apps/: Contains the main applications (in this case, my-app).
  • libs/: Contains shared libraries (in this case, ui).
  • nx.json: Global configuration file for the NX workspace.
  • project.json: Project-specific configuration file.
  • package.json: Manages dependencies and scripts for the entire monorepo.

See the result at http://localhost:4200

NX is a great tool for managing monorepos, helping you save time, boost productivity, and organize your codebase in a structured way. Whether you're a frontend, backend, or fullstack developer, NX can support you in building large-scale systems with ease.