Search code examples
reactjsreduxnext.js

How can I use server-side Redux in Next.js v13.0 with the help of app directory?


can we use Redux with Next.js v13 by using app directory? just like before, using the Next.js Redux wrapper. or if we can use then, is there any example available to use server-side Redux in Next.js 13?

I am going to use new Next.js v13 because of new layout update so, can we create a server side state by using app directory?

It seems that they are already using Redux, but if I implemented Redux as per the source code, then I am receiving the error of React createContext.

what should I do? What would the code be in an online editor?


Solution

  • From the Next.js beta documentation:

    In Next.js 13, context is fully supported within Client Components, but it cannot be created or consumed directly within Server Components.

    'use client';
    
    import { createContext, useContext, useState } from 'react';
    
    const SidebarContext = createContext();
    
    export function Sidebar() {
      const [isOpen,*emphasized text* setIsOpen] = useState();
    
      return (
        <SidebarContext.Provider value={{ isOpen }}>
          <SidebarNav />
        </SidebarContext.Provider>
      );
    }
    
    function SidebarNav() {
      let { isOpen } = useContext(SidebarContext);
    
      return (
        <div>
          <p>Home</p>
    
          {isOpen && <Subnav />}
        </div>
      );
    }
    

    More details are here: Next.js documentation

    Another user asked about the same topic.