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.