Next.js Discord

Discord Forum

Single truth/source of data

Unanswered
Allegheny mound ant posted this in #help-forum
Open in Discord
Allegheny mound antOP
Let's say you have a dashboard with multiple components, where each component fetches its own data on the client side.

This means when 2 different components use the same data, the related API endpoint gets called twice.

What's a good structure to only have 1 source of data, like a store or context that provides data to all my components so they don't have to individually fetch data themselves?

Right now they get updated frequently enough, but it's just too many unnecessary requests.

I have a context right now, but I'm not sure where to make the initial requests to retrieve the data and add it to the context.

I'm also not sure how to update the context data frequently enough.

14 Replies

Is it truly a problem?
Or a premature optimization?
Over-fetching data isnt a problem until it becomes one
Is it "too many unncessary requests" because you say it is
or because there is a measurable degradation of service, performance or a noticable spike in your billing?
By the way if you're fetching client side, consider using a library like swr or react-query and it will handle deduping requests and loading data from a client side cache
"I have a context right now, but I'm not sure where to make the initial requests to retrieve the data and add it to the context." do that in the context provider, alongside the data you can also return a function that allows mutating them/triggering a refetch
This is not really Next.js related you may want to try a React Discord where you'll get more visibility on your questions
@linesofcode By the way if you're fetching client side, consider using a library like swr or react-query and it will handle deduping requests and loading data from a client side cache
Allegheny mound antOP
I am using React-query, however when navigating from view A to view B (using a Link element), I see the following requests being made in my Network tab, they're all from view B.

This is unnecessary because I already made a requests to projects on view A.
Maybe this is something for the React-query discord, sorry.
@Allegheny mound ant Maybe this is something for the React-query discord, sorry.
no problem to ask React questions here you'll just get better answers there
usually client-side data fetching will tend to query a lot
because it cannot tell if you want cached data or not
there are probably options to tell them "just fetch once and let me tell you when to update"
@Eric Burel there are probably options to tell them "just fetch once and let me tell you when to update"
Allegheny mound antOP
Yes there is, I just got informed about the react-query option staleTime which solves the issue for me.