How to usewindow object inside useEffect in Next.js
If you’re using React hooks, you can utilize the useEffect hook and check for the window object. This method is particularly suitable for functional components. Since the useEffect hook is part of React, it executes on the client side after the component mounts. Therefore, if you simply need to determine if the code is running on the client side, this approach works well. For instance, it’s useful for generating a random number without encountering server-side errors.
Example:
//index.js
import Head from "next/head";
import { useEffect } from "react";
export default function Home() {
useEffect(() => {
if (typeof window == "undefined") {
console.log("Variant 1: Application is on server side");
} else {
alert("Variant 1: Application is on client side");
}
}, []);
return (
<>
<Head>
<title>Create Next App</title>
</Head>
<main>
<h2>This is a demo page</h2>
</main>
</>
);
}
Output:
Detecting server vs client in NextJS application
Next.js, a popular React framework, helps you to build powerful web applications with ease. However, managing server-side and client-side execution can pose unique challenges. In this article, we’ll explore techniques for detecting server or client execution in Next.js applications.
Table of Content
- What is Server Side Rendering?
- What is Client Side Rendering?
- Detecting server vs client-side rendering
- 1: Using typeof window
- 2: Using process.browser
- 3: Using a custom flag
- 4: Using req object in getServerSideProps
- 5: Using window object inside useEffect