Skip to content

Can't build server components and client components in the same library #405

Closed
@rafa-apptronik

Description

Describe the bug

I am writing a component library with Vite and Storybook. It has mostly regular react components but some that have useState I've put "use client" at the top in order to be compatible with my Next.js app. This worked great until I needed to use this library with a non-typescript react app. Ok, I just compile the ts into js with vite build. But when I do, the .es file has a useState at the top that affects all components such that everything is now a client component. The component library and it's dist should mostly stay agnostic of server and client rendering, yet I'm having to jump through hundreds of hoops just to server render. I've gone through the vite server rendering docs and building docs and tried many permutations of solutions to no avail. I've ended up with a version that has the dist build for my react app and a version that doesnt for my Next app.

Reproduction

vite.new/react-ts

Steps to reproduce

Steps to reproduce:
Create new Vite app with yarn create vite my-vite-app --template react-ts
Write any two React components - one with useState and a "use client" at the top, one without either.
Run vite build or yarn build
Go to any Next app possibly created with create-next-app and link your new library
Try to import your server component (the one without state) and see that you can't because the .es file has useState imported at the top.

System Info

System:
    OS: macOS 15.1
    CPU: (14) arm64 Apple M4 Pro
    Memory: 7.04 GB / 48.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 23.5.0 - ~/.nvm/versions/node/v23.5.0/bin/node
    Yarn: 1.22.22 - /opt/homebrew/bin/yarn
    npm: 10.9.2 - ~/.nvm/versions/node/v23.5.0/bin/npm
  Browsers:
    Chrome: 131.0.6778.265
    Safari: 18.1
  npmPackages:
    @vitejs/plugin-react: ^4.3.4 => 4.3.4 
    vite: ^6.0.7 => 6.0.7

Used Package Manager

yarn

Logs

You're importing a component that needs useState. This React hook only works in a client component. To fix, mark the file (or its parent) with the "use client" directive.

Validations

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions