Next.js Discord

Discord Forum

Make fetch from an api and share the data in different nodes of the tree

Answered
Wood Duck posted this in #help-forum
Open in Discord
Wood DuckOP
Hello, I have a component that is used in several pages and requires data from an api, I would like to know if it is correct to use the context of react to fetch and share that data in the component to call the api only once, I understand that for this I would use 'use client' in the context, but would lose the advantages of ssr? If you could give me other alternatives to share data at different levels, I would appreciate it.
Answered by Rafael Almeida
what is useTestimonialService? it is named like a hook but the return type doesn't seem to be from an actual react hook. if it is calling fetch then you don't need to worry about duplicated requests if you render this component multiple times
here are the docs about the requests memoization: https://nextjs.org/docs/app/building-your-application/caching#request-memoization
View full answer

11 Replies

is this component already a Server Component? if it is, then you can just use fetch and Next will dedupe the requests. and no, adding 'use client' doesn't stop the component from being pre-rendered in the server, it just means it will render both in the server and in the client
Wood DuckOP
@Rafael Almeida I'm doing something like this on my testimonials component:
What I'm looking for is to make a single call to the API, I don't know if this way is correct for what I want to do
what is useTestimonialService? it is named like a hook but the return type doesn't seem to be from an actual react hook. if it is calling fetch then you don't need to worry about duplicated requests if you render this component multiple times
here are the docs about the requests memoization: https://nextjs.org/docs/app/building-your-application/caching#request-memoization
Answer
Wood DuckOP
yeah this is fine, these requests are gonna be deduped
Wood DuckOP
@Rafael Almeida Another question, I just opened the project again and I get this error, it was solved by changing from export const to export default in the component file. It is better to use the export default or the const, I use the export const to have an index at component folder level and I doexport * from './product-card.tsx and so everything that comes from components is : import {ProductCard} from '@/components'. But now I'm getting a lot of errors in all components, which didn't happen before 😄.
usually this error is caused by a circular dependency, so you need to check your modules import graph. I don't recommend doing barrel exports, imo it's better to just import the components by their file (like from '@/components/ProductCard')
Wood DuckOP
I will make the changes, thank you very much for your help.