Anton
Anton

Reputation: 1001

Nextjs mix SSR and client data in components

I faced the situation when the same component shows mixed data when randomisation involved, html get jumbled data partially from SSR and partially from client rendering.

Here is the code :

const Component = (props) => {
    const rand = Math.random();
    console.log('==========================', rand);

    return <a href={rand}>{rand}</a>
}

The result is following.

SSR :

========================== 0.30408232064749563

Client rendering :

========================== 0.6842738761932372

Result HTML :

<a href="0.30408232064749563">0.6842738761932372</a>

So the a tag get old SSR value in href while text value get updated.

Upvotes: 0

Views: 1092

Answers (1)

bcjohn
bcjohn

Reputation: 2523

If you want to make the data identical in SSR and CSR, you should create Math.random() in getInitialProps and pass it by props.

const Component = props => {
  console.log(props.rand)
}

Component.getInitialProps = async () => {
  const rand = Math.random();
  console.log(rand);

  return {
    rand
  }
}

Upvotes: 1

Related Questions