Differentiating a component mounting or hydrating in React 16.1.1

Viewed 525

I have a ScrollToTopOnMount as implemented here with

componentDidMount(prevProps) {
  window.scrollTo(0, 0)
}

Which works great, except when I combine this with SSR and hydrating, my page snaps to the top when the hydration happens.

Other answers such as this one gave me hope that there may be some way to discriminate between whether a component is legitimately mounting, or just being hydrated. However, this does not seem to be the case as of react-dom 16.1.1, where both the server and the client appear to call componentWillMount.

Is there a way to have an lifecycle method determine whether it's being mounted where there is no DOM or hydrating an existing node?

1 Answers

ReactDOM.hydrate has a callback when it completes. One solution would be to set and un-set a global var window.hydrating = true and differentiate based on that when the component mounts.

Related