Best practices for sharing data between components in Next.js?
Unanswered
Red-naped Sapsucker posted this in #help-forum
Red-naped SapsuckerOP
In react, I would use something like redux to share data between components, that are in different places on the component tree. Is this the preferred way when working with next.js? How do you do it?
102 Replies
Usually I fetch the data at page render, using the next 13 App router
Directly from the DB
Red-naped SapsuckerOP
And then you pass everything down through props ?
yes
no redux needed at all
Red-naped SapsuckerOP
One reason to use something like redux is so you don't have to do that
if they arent client components you dont need to.
you can fetch it in every server component that needs data
not just the page
Oh yeah, I forgot to mention that
Red-naped SapsuckerOP
Ok but what if multiple components fetch the same data? Not necessarily using
fetch() ?@Red-naped Sapsucker Ok but what if multiple components fetch the same data? Not necessarily using `fetch()` ?
This is a Example fetching the database with a Server Component, it directly fetches the database, no
fetch at all.forgot to put content on the li itself, but I think the point stills intact
@Red-naped Sapsucker Ok but what if multiple components fetch the same data? Not necessarily using `fetch()` ?
then use cache to dedup the requests. and “not necessarily using fetch†should only apply to databases and old packages. if you are intentionally using axios you are making a bad choice 🙂
@DirtyCajunRice | AppDir then use cache to dedup the requests. and “not necessarily using fetch†should only apply to databases and old packages. if you are intentionally using axios you are making a bad choice 🙂
Red-naped SapsuckerOP
Yeah that will probably be database queries at some point. So I guess the database should handle the caching? Or what do you mean by "use cache" ?
wrap your call in it and all calls made in the same request are deduped and only 1 call is made
Worth mentioning:
fetch requests are automatically deduplicated.Red-naped SapsuckerOP
Oh this looks fancy. I'm intrigued, thanks 

You're welcome 😄
Red-naped SapsuckerOP
Oh this is 

I love it
Red-naped SapsuckerOP
Consider a different example tho. Having a simple user login, where would you store a userid, so you can use it on subsequent pages/requests all over your app?
Surely, there must be a different way than having that userid passed on via page params
@Red-naped Sapsucker Consider a different example tho. Having a simple user login, where would you store a userid, so you can use it on subsequent pages/requests all over your app?
I didn't have to do that as I use
next-auth, can you give me another example?Red-naped SapsuckerOP
Alright, consider some other session data like a shopping cart
European sprat
you can do it any way you want really, including using redux or other state management libraries
Red-naped SapsuckerOP
I figured I can do it any way I want, but I was asking for best practices or experiences
European sprat
well for your cart example, if you used react context you could wrap the children in a layout.tsx file with a context provider then any child client components can consume the context through hooks
i think redux works the same way having a provider wrapper and then using a hook to get state
Red-naped SapsuckerOP
Also afaik redux works on the client, does that work with server components as well?
European sprat
the component would need "use client" at the top but your example of a shopping cart would be a client component since that's going to be interactive
Red-naped SapsuckerOP
I guess? I'm new to next.js so I have not a full grasp on the server component thing yet. How does it work when you use
next-auth, are all components using a userid provided by that library client components as well?European sprat
i'm not familiar with next-auth
i skimmed this and it gives you a good overview of using react context and consuming it
Red-naped SapsuckerOP
I'm going to look at it when I have time, thanks 🙂
European sprat
good luck. the whole nextjs/server component/client component thing is a lot to wrap your head around
@Red-naped Sapsucker Alright, consider some other session data like a shopping cart
you could use localstorage, session storage, or indexdb for this too
@Marchy you could use localstorage, session storage, or indexdb for this too
Red-naped SapsuckerOP
on the server side?
@Red-naped Sapsucker on the server side?
I guess it depends on what you're sharing and why
Red-naped SapsuckerOP
i guess theres packages that provide those APIs in a node environment
@Red-naped Sapsucker i guess theres packages that provide those APIs in a node environment
no, there isn't because those are browser apis
Red-naped SapsuckerOP
i know
you seemed to suggest to use those on the server side anyways, so i assumed there would be packages provide similar functionality for node
*that
You mentioned passing data between components - are you not talking about client side logic?
the why you need to pass data between components is important for knowing what approach you should take.
Red-naped SapsuckerOP
I asked about sharing data between components, those ideally being server components in the context of next.js. Passing data down as properties was mentioned as one possible approach. But my question was more of a general nature. What are best practices to share data aka. state between components in next.js
The short answer is don't
Red-naped SapsuckerOP
One example was a userid, another was a shopping cart
it's unneccessary 99% of the time
Red-naped SapsuckerOP
?
Cart data would be fine for something like local storage. You don't need it in the server, it's just the values they're going to submit when they check out.
Unless you want the analytics, but then you'd want to move into something like a redis cache
Red-naped SapsuckerOP
So you're telling me when I actually have the requirement to have some sort of session related data, all my components using it have to go client side
@Red-naped Sapsucker So you're telling me when I actually have the requirement to have some sort of session related data, all my components using it have to go client side
No, I have no idea what you mean
why would you need session data on the server. HTTP requests should be slim and direct. There's no long-running server state.
why would you need session data on the server. HTTP requests should be slim and direct. There's no long-running server state.Red-naped SapsuckerOP
Ok. Simple case. User logs in. Where do I put the userId so all my components can access it? In a regular react SPA, I'd throw that into my state manager aka. redux or whatever
Why do all of your components need to access the user id?
Red-naped SapsuckerOP
Don't take it literally
2 components. User Panel and data fetching main content component
Well, a user panel would render the user data
Authentication and authorization are handled through headers and cookies, you don't need all of it to make a fetch
reset your brain. Its NOT a single page app. Its NOT a client only site. it is a very different way of data management. throw out all your preconceived decisions and start over
Next is closer to HTML than an SPA
you will be glad you did once it all makes sense
With an SPA you send the entire client on the first request. Next allows you to stream areas of the page independently so they can be loaded on demand, and server actions allow you to use your database source as your state
European sprat
but as i said before, there's nothing stopping you from using a state management library that client components can consume for when you do need to pass those values around and it can't be done in a server component
Red-naped SapsuckerOP
Ok then walk me through it. I have a page with some header, which contains a
<UserPanel/> component. This component should fetch (by userid) the username and icon. On the same page, i have a component idk.. <SupportTickets/>, which fetches (by userid) and displays all support tickets created by that user. Does that make sense in the context of next.js?You fetch the data in the server components for each component. They are bundled in SSR by next.
Red-naped SapsuckerOP
Yeah ok, I fetch the data, but I need the userId of the logged in user to do that. Where do I get that userId from?
middleware
/ cookie token check
European sprat
i get mine from a jwt
You get it from the same place you get it in the user panel.
Red-naped SapsuckerOP
Yeah my whole point in this post here was to find out where such a place could be
So its cookies or request headers
Red-naped SapsuckerOP
So when I dont want to pass through component params or url params, i need to store on the client and send with the request via cookies/headers
Which kinda makes sense, since server components are "stateless" ? Is that correct?
Red-naped SapsuckerOP
I read that but i'm not sure what you were going for with it
But I have a question. Aren't next.js apps deployed on regular javascript server runtimes? Node for example?
@Red-naped Sapsucker But I have a question. Aren't next.js apps deployed on regular javascript server runtimes? Node for example?
European sprat
they can be. i think the primary method is people using vercel's infrastructure which is serverless
i deploy mine via AWS ECS in a docker container that runs node. "output: standalone" in the nextjs config will create a standalone build you can serve with node
@European sprat https://www.youtube.com/watch?v=RTAJ-enfums
Red-naped SapsuckerOP
I'm watching this right now and what he does is, he adds a context provider, just like you can do in a react SPA, and then adds
'use client' to that provider component. My question now is, since that provider basically wraps the whole layout/component tree, do all child components remain as server components?European sprat
yeah you can mix them
Red-naped SapsuckerOP
Does that have any performance impact on the child server components? Or is performance only impacted when I start using client components that hook into that context provider?
European sprat
i don't know about performance specifically but there's nothing wrong with using child components for when you need that interactivity
and client components still get pre-rendered on the server so you get that SSR benefit if it's what you are looking for with next
@Marchy https://nextjs.org/docs/getting-started/react-essentials
European sprat
this page is a really good read i still find myself coming back to to help understand things
Red-naped SapsuckerOP
Yeah I've been reading there a lot as well, but it's also nice to be able to talk someone about it from time to time
Also i'm not really looking for anything with next.js, just been playing around with it for the last 3 days
Never tried SSR until now so that's what i'm trying to wrap my head around at the moment
I like the development experience with nextjs and the docs are very well written
Red-naped SapsuckerOP
Anyways. Thanks to everybody involved, I appreciate your patience. I'll probably come back with more questions at some point 🙂
European sprat
have fun