๋ชฉ๋กSSR (2)

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

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

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์ž…๋‹ˆ๋‹ค. ๊ณ ๋กœ ๋ธŒ๋ผ์šฐ์ €๊ฐ€์•„๋‹Œ ์„œ๋ฒ„์—์„œ ..

๐ŸŒท Next JS 2023. 1. 5. 15:00