Fetch data in Next app to be available across all app
I am building a NEXT app and I have 4 routes in it, I already have reusable components, but I don't really know how to properly fetch data in one single place so that it would be accessible across all routes. Help?
1 Reply
I would create a React context and place it in the root layout, wrapping the rest of your app.
E.g. if you need the current user information, create a UserProvider
... and then just place it in your root layout.
You can then use
const { user } = useUser()
in any client component.
More info here:
https://react.dev/learn/passing-data-deeply-with-context
https://react.dev/reference/react/createContext