I'm building a isomorphic application, but I'm using a third-party component that only renders on the client. So, particularly for this component, I need to only render it when I'm rendering in the client.
How do I detect if I'm at the client or at the server? I'm looking for something like isClient()
or isServer()
.
You could also just use the
use-ssr
React hookYou can use reacts lifecyle events (e.g.:
componentDidMount
) to detect server/client side rendering.Examples
As Hook
Usage
See below (Functional Component)
As Functional Component
Usage
As Class Component
Usage
You can check if global
window
variable is defined or not. as in browser it should always be defined.Internally, React uses a utility called
ExecutionEnvironment
for this. It implements a few useful properties likecanUseDOM
andcanUseEventListeners
. The solution is essentially just what's suggested here though.The implementation of
canUseDOM
I use this in my application like this
EDIT This is an undocumented feature that shouldn't be used directly. Its location will likely change from version to version. I shared this as a way of saying "this is the best you can do" by showing what the Facebook team uses internally. You may want to copy this code (it's tiny) into your own project, so you don't have to worry about keeping up with its location from version to version or potential breaking changes.
ANOTHER EDIT Someone created an npm package for this code. I suggest using that.
You can also use
componentDidMount()
, as this lifecycle method is not run when the page is server-side rendered.You can create one useful utility with the help of the
exenv
package.And use it like this
And the function will only be called on client side, and it will log on server side that this function has been called on client side if you set
NODE_ENV=development
(It's typescript, remove types for JS :) )