skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. Below is an example of how you can pass context information to your server components efficiently using React and the Context API:

    import React, { createContext, useContext } from "react";
    
    // Create a context for the app context information
    const AppContext = createContext();
    
    // Context provider component
    const AppContextProvider = ({ children }) => {
      const appContext = {
        username: "john_doe",
        role: "admin",
        // Other context data...
      };
    
      return <AppContext.Provider value={appContext}>{children}</AppContext.Provider>;
    };
    
    // Custom hook to access app context
    const useAppContext = () => {
      return useContext(AppContext);
    };
    
    // Server component that uses the app context
    const ServerComponent = () => {
      const appContext = useAppContext();
    
      // Use appContext to perform server component functionality
      const greeting = `Hello, ${appContext.username}! You are an ${appContext.role}.`;
    
      return <div>{greeting}</div>;
    };
    
    // Example usage
    const App = () => {
      return (
        <AppContextProvider>
          <div>
            <h1>App</h1>
            <ServerComponent />
          </div>
        </AppContextProvider>
      );
    };
    
    export default App;
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search