Isolating effects into empty components in the new App Router
Unanswered
kBazilio posted this in #help-forum
kBazilioOP
The new App Router promotes the usage of the
So what I do is I create a new component with
But creating a component that does not render any JSX whatsoever each time I need to do a
use client directive to mark components as client-side only, making the JS of all of its direct dependencies to be added client-side, thus increasing bundle size. But what if most of my dependencies could be server-side, but I just need to use a useEffect hook in my component? I don't want the JS of all those other dependencies to get bundled because of that one useEffect hook call and miss out on potential optimization.So what I do is I create a new component with
use client directive where I use the useEffect hook and make this component return null. Then I import this "empty" component into my original component, and now I can avoid using use client on that level, because it's been moved down the tree.But creating a component that does not render any JSX whatsoever each time I need to do a
useEffect feels like such an anti-pattern! Should I even be doing that?9 Replies
Standard Chinchilla
what are you trying to ackomplish in the useEffect
@Standard Chinchilla what are you trying to ackomplish in the useEffect
kBazilioOP
It doesn't really matter much to be honest, this isn't a specific case in one particular place in the code, it's more of a global issue that I'm facing. For the sake of example we can say that I'm logging current date to the console.
Standard Chinchilla
But at that point you don't need a useEffect
And there is no need to make a client component
If you need to fetch data in a useEffect you would ideally want to place the useEffect in a component as far down the tree as possible where you would use that data to render elements in the client component
Usually you can fetch data in a server component now with the app router
@Standard Chinchilla Usually you can fetch data in a server component now with the app router
kBazilioOP
But I wasn't talking about fetching data. Again, it might very well be something that can only be done client-side. Thing is, I don't want to make the entire component bundle all of its dependencies because of that one useEffect. So I do put the said effect down the component tree. But I do so by putting it into an empty component that doesn't render any JSX. And I'm wondering if it's the correct approach because it feels wrong.
Standard Chinchilla
No it’s not the correct approach because you don’t need an effect if you’re not rendering anything
Also in react you ideally want to break up big components into smaller pieces. So the ones you need to use useefect just turn into a client component