Next.js Discord

Discord Forum

Issues when importing from `index.ts` using app directory

Unanswered
Mr.Robot posted this in #help-forum
Open in Discord
Please look into the following sandbox, where I highlight the issue.

https://stackblitz.com/edit/stackblitz-starters-fhjavm?file=components%2Fcomp-client.tsx

I have following structure of nextjs app
components
 ┣ index.ts
 ┣ comp-client.tsx
â”— comp-server.tsx
 app
 â”— page.tsx
 


In page.tsx, I have following code
import { CompServer } from '@/components';
export default function Home() {
  return <CompServer />;
}


In comp-client.tsx, I have following code
import { useEffect } from 'react';
export const CompClient = () => {
  useEffect(() => {}, []);
  return <h1> Client</h1>;
}


In comp-server.tsx, I have following code
export const CompServer = () => <h1> Server</h1>;


In index.ts, I have following code
export * from './comp-client';
export * from './comp-server';


I am getting the following error You're importing a component that needs useEffect. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.

Why am I getting this error, only when I am importing comp-server in page.tsx

12 Replies

it's because useEffect only work in client component so you need to add 'use client' at the top of the file to mark it as a client component
I get that. But I am only importing comp-server and it should work as I am not importing comp-client
it is working in stackblitz?
ah I got it
well, it might be better to separate them
https://stackblitz.com/edit/stackblitz-starters-ju1jbp
as you can see, I just put 'use client' in components/client/index.ts and it still render as client component
"I encountered a similar issue on my project. However, I am curious to know why it doesn't work without using the use client directive. In my case, all the components are exported from the index.ts file. Some of them are directly imported in page.tsx, while others are imported in other components that are themselves using the use client directive."
because it would mark the server component to become client component
Thank you for your help, Ray. I already know the solution, but I'm curious about why importing just the server components from index.ts throws an error. This is how es module works or this is implemented by Nextjs team.
more like how es module work and 'use client' is react stuff😆