0

In NextJs v13 I am using a client-side component that groups all providers. Such as the example below with a single provider:

providers.tsx

'use client';

import WindowProvider from "@/providers/window-provider";

export function Providers({ children }: { children: React.ReactNode }) {
  return (
    <WindowProvider>
      {children}
    </WindowProvider>
  );
}

And then I use this component in the RootLayout:

layout.tsx

export default function RootLayout({
                                     children,
                                   }: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
    <body>

    <Providers>
      {children}
    </Providers>
    </body>
    </html>
  )
}

Despite specifying that the provider is a client-side component with use client I am getting an error when client-side window is called from the provider as shown below:

"use client";

import React, { useState, useEffect } from 'react';
import WindowContext, {WindowDimensions} from './window-context';

const WindowProvider = ({ children }) => {
  const [dimensions, setDimensions] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });

  useEffect(() => {
    function handleResize() {
      setDimensions({ width: window.innerWidth, height: window.innerHeight });
    }

    window.addEventListener("resize", handleResize);

    return () => {
      window.removeEventListener("resize", handleResize);
    };
  }, []);

  return (
    <WindowContext.Provider value={{ dimensions: dimensions, setDimensions: setDimensions }}>
      {children}
    </WindowContext.Provider>
  );
};

export default WindowProvider;

Question: Why is the client-side provider being executed on the server side? And hence failing as window is not defined? How do I fix that?

FYI, the above is just a simple example to illustrate the issue.

Rinor
  • 1,790
  • 13
  • 22
  • It does help, thx. So there is no way around to checking if it is defined and handling those cases. – Rinor Jul 17 '23 at 12:30
  • Which rendering mode you are using? – Arjun Shrivastava Jul 17 '23 at 12:58
  • @ArjunShrivastava I am using client side rendering on this instance. The issue seems that despite this being client side it is run in the server side and then hydrated in the client side. hence the code was executed – Rinor Jul 17 '23 at 19:48

0 Answers0