Window is not defined in Next.js React app
window
, meet useEffect
. Remember, only in useEffect
, to prevent awkward window not defined
moments in your Next.js SSR journey.
How to avoid window pains in SSR
In the Next.js world, the sun shines (code runs) on both server and client land. window
can be found sunbathing in the browser, but in the server... well, no windows there—thus, the infamous "Window is not defined" error.
Using dynamic import for client folks only
For modules that do hangouts only in browser land (client) - dynamic import them. This way, they won't sneak into server-side rendering (SSR) and create scenes.
Custom hooks for window resizing
Does your component need to keep an eye on the window size? Create a custom hook for that!
Lifecycles and Hooks: The Rescue Squad
componentWillMount
has left the building. The new sheriff is either useEffect
or componentDidMount
. Remember, they're the gatekeepers to accessing window
.
Using componentDidMount for window access
When using class components, the componentDidMount
lifecycle method is the bouncer - "You shall not pass until I'm done!", keeping window
safe.
Functional components with useEffect to the rescue
For functional components, useEffect
is the hero, similar to componentDidMount
, componentDidUpdate
, and componentWillUnmount
bunched into one.
Universal libraries and Component Redesign
The code needs to run on both browser and server land. So when it comes to handling window
, universal or isomorphic libraries get the job done! They work both sides, server and client.
Component care with window in server-side rendering
Take some time to redesign components so they understand what server-side rendering means and safely handle window
.
The Next.js code Garden
Growing a beautiful Next.js code garden demands structured planting, nourishment, and regular prunes.
Planting client-side code wisely
Plant (keep) client-side code in its own plot (section). It's like having a herb garden in a backyard - efficient and easy to maintain.
Regular clean-up saves you pain
Listened to events like resize
or scroll
on window
? When the season changes (component unmounts), make sure the plot (memory) is clean and ready for next season(component).
Conditional rendering is your friend
Use conditional rendering to ensure right plants (components) are grown in a suitable climate (environment). This helps to avoid unexpected frosts (React hydration errors).
Was this article helpful?