Managing server vs browser in SSR React

Kevin McCarthy
Mar 26, 2021

--

TL:DR set state in componentDidMount() to keep track of if you’re on the client or server.

For server-side-rendered (SSR) react, the componentDidMount() only runs on the client, not in the server. So you can do something like

class Root extends Component {
constructor(props) {
super(props);
this.state = { isClient: false }
}
componentDidMount() {
this.setState({ isClient: true })
}
}

to manage which code should only run in the browser by wrapping them in if(isClient) .

So if isClient is false we know we’re on the server and if isClient is true we know we’re on the client.

This had caused me a lot of pain in the past! so happy to have found this.

--

--

No responses yet