3

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?

Andrey Fedorov
  • 9,148
  • 20
  • 67
  • 99
  • Why are you trying to scrollTop? Because hydrate will always run componentDidMount. It scrolls to the top because it's what your are telling it to do – João Cunha Nov 15 '17 at 13:10
  • the link explains the use case a little more generally, but simply, I'd like to scroll to top when someone switches sections on my page. however, when the page is loaded for the first time, I'd like to behave slightly differently during hydration, since the component isn't really mounting, it's hydrating, which is something in between an initial mount and an update. – Andrey Fedorov Nov 15 '17 at 19:27

1 Answers1

4

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.

Andrey Fedorov
  • 9,148
  • 20
  • 67
  • 99