React hydration on SSR

Viewed 1395

I am not fully understood React's Server Side Rendering. What's difference behaviors occurred between two examples?

First

function Test() {
  const context = useContext(AuthContext)
  const { user } = context

  return (
    user ? <h1>User</h1> : <h1>No User</h1>
  )
}

export default withApollo({ ssr: true })(Test)

===> Error occured Text content did not match. Server: "No User" Client: "User"

Second

function Test() {
  const context = useContext(AuthContext)
  const [ user, setUser ] = useState(null)

  useEffect(() => {
     setUser(context.user)
  }, [])

  return (
    user ? <h1>User</h1> : <h1>No User</h1>
  )
}

export default withApollo({ ssr: true })(Test)

===> No Error.

What's difference? Why the first one make error but second not? In Postman, when I request this component route for checking server side response, both's response are same (No User).

What point is make difference? useEffect only excuted in client side, I know, but how about first one also updated to No User to User. when is hydration point, render point ?

1 Answers

I can't be 100% on this without seeing how AuthContext is set up on both client and server renders, but following logically backwards it seems like the difference here is that AuthContext is already populated with a value before the client's first render, but not before the server render.

That's why in the first example your server render contains no user, but your first client render contains a user. No user populated in AuthContext on the server, AuthContext populated with user on the client, so first client render is different from the server render hence the error.

In the second example, because you're reading user from state which is only set from the AuthContext after the first client render using useEffect, the first render on the client also contains no user - hence no difference between server render, and first client render, and no error.

Related