๐Ÿค ์€์ง€log ๐Ÿค

[NextJS] NextJS ์—์„œ window ๊ฐ์ฒด๊ฐ€ ์—†๋‹ค๊ณ  ํ• ๋•Œ ๋ณธ๋ฌธ

๐ŸŒท Next JS

[NextJS] NextJS ์—์„œ window ๊ฐ์ฒด๊ฐ€ ์—†๋‹ค๊ณ  ํ• ๋•Œ

Eun_zii 2023. 1. 5. 15:00

Next.js์—์„œ ์ œ๊ณตํ•˜๋Š” SSR, ํ•˜์ง€๋งŒ ์šฐ๋ฆฌ๋Š” SSR์—์„œ ์‚ฌ์šฉํ•˜์ง€ ๋ชปํ•˜๋Š” ๊ฐ์ฒด์ธ window ๊ฐ์ฒด๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ๊ฐ€ ๋งŽ์Šต๋‹ˆ๋‹ค.

๊ทธ๋Ÿด๋•Œ ํ•ด๊ฒฐํ•˜๋Š” ๋ฐฉ๋ฒ• !

1. typeof ๋ฅผ ์‚ฌ์šฉ.

if(window){...} 
// window is not definde ์—๋Ÿฌ๋ฐœ์ƒ

if(typeof window !== undefined) {...} 
// ์ •์˜๋˜์ง€์•Š์€ window์˜ ํƒ€์ž…์ด๊ธฐ๋–„๋ฌธ์— undefied๊ฐ€ ๋ฐœ์ƒ -> ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

 

๊ฐ„๋‹จํ•˜๊ฒŒ ์ด๋Ÿฌํ•œ ๋ฐฉ๋ฒ•์œผ๋กœ window๊ฐ์ฒด๊ฐ€ ์žˆ๋Š”์ง€ ์ฒดํฌํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ์žˆ์Šต๋‹ˆ๋‹ค.

 

2. useEffect๋ฅผ ์‚ฌ์šฉ.

useEffect(()=>{
	// ์•ˆ์—์„œ window ๊ฐ์ฒด๋ฅผ ์‚ฌ์šฉ
},[])

 

useEffect๋Š” DOMํ˜•์„ฑ ํ›„์— ์‹คํ–‰์ด ๋˜๋Š” hook์ž…๋‹ˆ๋‹ค.

๊ณ ๋กœ ๋ธŒ๋ผ์šฐ์ €๊ฐ€์•„๋‹Œ ์„œ๋ฒ„์—์„œ window๋ฅผ ์ฒดํฌ๋ฅผ ํ•˜์ง€ ์•Š๋Š” ๋‹ค๋Š” ๊ฒƒ์ด์ฃ .

react๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด์„œ ๊ฐ€์žฅ ํŽธํ•˜๊ฒŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์ด ์•„๋‹๊นŒ ์‹ถ์Šต๋‹ˆ๋‹ค.

 

3. dynamic์„ ์‚ฌ์šฉ

import dynamic from 'next/dynamic'

const ComponentsWithNoSSR = dynamic<{props:type;}>( 
// typescript์—์„œ props๋ฅผ ์ „๋‹ฌํ• ๋•Œ interface๋ฅผ ์ •์˜ํ•ด์ค๋‹ˆ๋‹ค.
  () => import('./components/Component'), 
  // Component๋กœ ์‚ฌ์šฉํ•  ํ•ญ๋ชฉ์„ importํ•ฉ๋‹ˆ๋‹ค.
  { ssr: false } 
  // ssr์˜ต์…˜์„ false๋กœ ์„ค์ •ํ•ด์ค๋‹ˆ๋‹ค.
);

const App = () => {
  return(
    <div>
    	<Components/> 
        // ํ•ด๋‹น ์ปดํฌ๋„ŒํŠธ๋Š” SSR๋กœ ๋ถˆ๋Ÿฌ์˜ฌ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
    
    	<ComponentsWithNoSSR/> 
        // ํ•ด๋‹น ์ปดํฌ๋„ŒํŠธ๋Š” ssr:false์ด๊ธฐ ๋•Œ๋ฌธ์— ์„œ๋ฒ„์‚ฌ์ด๋“œ ๋ Œ๋”๋ฅผ ํ•˜์ง€์•Š์Šต๋‹ˆ๋‹ค.
    </div>
  )
};

 

next.js์—์„œ ์ œ๊ณตํ•˜๋Š” dynamic์ด๋ผ๋Š” ํ•จ์ˆ˜๋กœ ssr์˜ต์…˜์„ ๊บผ์ค„ ์ˆ˜ ์žˆ์œผ๋ฉฐ,

์ด๋กœ ์ธํ•ด window๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์ปดํฌ๋„ŒํŠธ์—์„œ ์—๋Ÿฌ๊ฐ€ ๋‚˜๋Š” ๊ฒƒ์„ ๋ง‰์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

728x90