Next.js Discord

Discord Forum

Index files and "use client"

Unanswered
Himalayan posted this in #help-forum
Open in Discord
HimalayanOP
If we define a function which is used client side, we flag it with "use client". If I rexport this function from a folder index.js/ts does this file also need the "use client" flag?

6 Replies

Wood Thrush
Any components inside your 'use client' will be client component, including functions. Irrespective of where you import it.
So if you have functions which should run on server side, don't put them inside 'use client'.
HimalayanOP
So a function exported from a file using "use client" and then reported from an index file needs the index file to also declare "use client" if the component is being imported from the index?
Wood Thrush
Could you rephrase the sentence?
HimalayanOP
So in a structure like this:

folder/
---file1.ts
---index.ts
otherFolder/
---file2.ts


- file1 declares "use client" and exports a function.
- index.ts re-exports the function (export {someFunc} from "./file1.ts")
- file2 imports the function from folder (import {someFunc} from "../folder")

Does index.ts also need "use client"?
Northern Wheatear
No thats not necessary it would still work as a client component
@Himalayan So in a structure like this: folder/ ---file1.ts ---index.ts otherFolder/ ---file2.ts - `file1` declares `"use client"` and exports a function. - `index.ts` re-exports the function (`export {someFunc} from "./file1.ts"`) - `file2` imports the function from `folder` (`import {someFunc} from "../folder"`) Does `index.ts` also need `"use client"`?
Wood Thrush
No, that is not necessary. As mentioned earlier, try to think of this way to make it easier for you:
* Every component is server by default.
* If you import any component which is marked as 'use client' inside any other component, you don't disturb the harmony and doesn't require anything extra on your part. That is, if you have imported in page.tsx for example which is server-side, it will stay server-side, it won't change itself to client-side component just because you imported a client-component or function.
* However, this is the important takeaway, in your file1.ts file which you have marked as 'use client' on the top, if you have imported any component inside of that file, let it be client-side or server-side component, they will be converted to client-side automatically.