Undefined ‘window’ in Gatsby using Hooks
Having the error ‘window is not defined’ in Gatsby is not a big deal, but it might jolt newbies especially when wrapping your head around Server-side Rendering.
You might not encounter this error on development, but when you try to build your Gatsby app for production, this error can pop up on your face.
This has been solved before, and the commonest way you can find it on the internet is either through the debugging HTML builds on the Gatsby documentation or simply calling the window object on ComponentDidMount lifecycle.
The problem is clear by now, the window object wants to build on your server but it not available there so you need your window to be available in your client before calling it, simple.
This blog assumes you already know your way around Gatsby.
For example, I have a feature in my gatsby app that requires the current base URL and query parameters. In the src/hooks directory, I will create a file called getUrlParameter.js.
By this, the window object and some of the properties are now available and you can pass them to your components like:
In case you want to read further regarding hooks, I found this post very useful.
That is all 👌.