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
FluX
FluX2w ago
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
"use client"

interface UserContext {
user: any
}

const UserContext = createContext<UserContext | null>(null)

export const UserProvider = ({ children }: { children: React.ReactNode }) => {
const user = trpc.public.user.me.useQuery()
// ^ you could also do a simple fetch inside useEffect and store the user in useState

return (
<UserContext.Provider value={{ user }}>{children}</UserContext.Provider>
)
}

export const useUser = () => {
const context = useContext(UserContext)

if (!context) {
throw new Error("useUser must be used within a UserProvider")
}

return context
}
"use client"

interface UserContext {
user: any
}

const UserContext = createContext<UserContext | null>(null)

export const UserProvider = ({ children }: { children: React.ReactNode }) => {
const user = trpc.public.user.me.useQuery()
// ^ you could also do a simple fetch inside useEffect and store the user in useState

return (
<UserContext.Provider value={{ user }}>{children}</UserContext.Provider>
)
}

export const useUser = () => {
const context = useContext(UserContext)

if (!context) {
throw new Error("useUser must be used within a UserProvider")
}

return context
}
... and then just place it in your root layout.
const RootLayout = ({ children }: { children: React.ReactNode }) => {
return (
<html>
<head></head>
<body>
<UserProvider>
{children}
</UserProvider>
</body>
</html>
)
}

export default RootLayout
const RootLayout = ({ children }: { children: React.ReactNode }) => {
return (
<html>
<head></head>
<body>
<UserProvider>
{children}
</UserProvider>
</body>
</html>
)
}

export default RootLayout
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

Did you find this page helpful?