I will need the context to do database queries so it is necessary to have some context information, I cannot use the context functions because they are on the client side, I can pass this context as args every time I call a server component, but can this be more efficient?
This is my app context provider code:
"use client";
import { createContext, useContext } from "react";
const Context = createContext({});
const ContextProvider = ({ children }: { children: React.ReactNode }) => {
let appContext = {/* Info */};
return <Context.Provider value={{ appContext }}>{children}</Context.Provider>;
};
const AppProvider = ({ children }: { children: React.ReactNode }) => {
return <ContextProvider>{children}</ContextProvider>;
};
const useAppContext = () => {
const context = useContext(Context);
return context;
};
export { AppProvider, ContextProvider, useAppContext };
2
Answers
Rather than keeping the full state on client side, you can split it between client and server side.
On the server side, since you cannot use the context apis, you can use something like Zustand. This way, you can keep all your database logic in server components, and keep the bare minimum (like browser apis, client interaction) in client components.
Below is an example of how you can pass context information to your server components efficiently using React and the Context API:
The appContext object contains some basic context data such as username and role. The ServerComponent uses the useAppContext hook to access the context and generates a greeting message based on the context data.