Good use of SWR #468
Replies: 4 comments 8 replies
-
hi @ErnestBrandi I prefer the second one, and you can also optimize the user call in Child component to passing down the prop export default function Page() {
return (
// you might have sth else here, or you can merge `Page` and `SomeComp`
<SomeComp />
- <Child />
)
}
export default function SomeComp(props) {
const { data: user } = useSWR('/api/user')
return (
{!user ? (
<Pogress />
) : (
+ <Child user={user} />
)
}
)
}
export default function Child(props) {
- const { data: user } = useSWR('/api/user')
+ const { user } = props // then here for sure we had a user
const { data: projects } = useSWR(() => '/api/projects?uid=' + user.id)
return (
{ !user && !projects ? (
<Pogress />
) : (
// projects.map()
)
}
)
} it can make the call more consistent that you won't have multiple renders overlapped between user hooks and projects hooks. the projects hook will be called always after user is resolved. |
Beta Was this translation helpful? Give feedback.
-
We're using the second pattern at Vercel. Also we created tons of "data hooks" such as: function useUser () {
return useSWR('/api/user')
} And then just use Because of that, we don't need to pass props around the tree. It's also easier to maintain (so we can easily compose a UI without caring about data props). SWR handles deduping automatically. So it's basically just an extra |
Beta Was this translation helpful? Give feedback.
-
I use more the second way, where each component fetch what it needs instead of passing via props. I additionally tend to prefetch in the parent when the child is going to be rendered conditionally, this way I already have the data in cache when the child is rendered. |
Beta Was this translation helpful? Give feedback.
-
Thanks for those answers :) I have another question. Since I started using SWR, I can't figure out any good use case for SSR anymore... Indeed, you can always display the page template (navbar, footer, etc) and populate it client side (showing a I know you can combine both of these worlds with Is there obvious situations where I should use SSR and not SWR (or just client side fetching) ? |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi, I have a few questions about how SWR should be used the best.
Let's consider the following 2 use cases
Use SWR in parent and pass down props
Use SWR in each individual component
I feel like this is a common question but, which method should be preferred ?
I know it is not so much related to SWR itself but more about having dumb/smart react component (still what's SWR opinion about that) ?
I also know SWR use cached data so there is nothing wrong (performance wise) by doing the second method.
Also, what about a combination of those two way of doing ? Would that make sense sometimes or would it just be messy ?
Thanks for your replies !
Beta Was this translation helpful? Give feedback.
All reactions