Next.js: Warning: Prop `src` did not match. Server. And images aren't updated

Created on 20 Feb 2020  路  6Comments  路  Source: vercel/next.js

Bug report

Describe the bug

Warning: Prop src did not match. Server. And images aren't updated when shuffling an array before rendering it

To Reproduce

Create an array outside of a component and shuffle it before rendering (When runs on server only)

Expected behavior

Shouldn't throw client and server mismatch and update the images correctly

reproduce or CodeSandbox

https://codesandbox.io/s/musing-cray-11zoo

import Link from "next/link";

const list = [
  {
    url: "/now.png",
    name: "Now"
  },
  {
    url: "/next.png",
    name: "Next"
  },
  {
    url: "/mdx.png",
    name: "MDX"
  },
  {
    url: "/lambda.jpg",
    name: "lambda"
  },
  {
    url: "/github.png",
    name: "github"
  }
];

const shuffledList = shuffleArray(list);

const index = () => {
  console.log(shuffledList);
  return (
    <div>
      <Link href="/about">
        <a>About</a>
      </Link>
      <div style={{ display: "flex", flexWrap: "wrap" }}>
        {shuffledList.map(item => (
          <div
            key={item.name}
            style={{
              border: "1px solid black",
              margin: "10px",
              textAlign: "center"
            }}
          >
            <img src={item.url} alt={item.name} style={{ width: "200px" }} />
            <p>{item.name}</p>
          </div>
        ))}
      </div>
    </div>
  );
};

export default index;

function shuffleArray(arr) {
  return arr
    .map(a => [Math.random(), a])
    .sort((a, b) => a[0] - b[0])
    .map(a => a[1]);
}

System information

  • Version of Next.js: 9.1.6

Additional context

No

Most helpful comment

Generally I'd just recommend not randomly shuffling stuff in the UI, but if you really want to you can use useEffect / setState

All 6 comments

Seems like correct behavior, if you change the order of items hydration won't happen correctly as you're moving items around.

Doesn't the shuffle run before rendering? i miss something here

The only two way i could avoid this is using SSR(getInitialProps) or client only(use useEffect and and store it in a state) but both have downside losing static optimisation or SEO

The code gets loaded both server-side and client-side and executes in both cases. That's the reason stuff gets shuffled twice.

Could you suggest a solution or should i go with SSR or set it in a state?

Generally I'd just recommend not randomly shuffling stuff in the UI, but if you really want to you can use useEffect / setState

Thanks

Was this page helpful?
0 / 5 - 0 ratings

Related issues

wagerfield picture wagerfield  路  3Comments

YarivGilad picture YarivGilad  路  3Comments

ghost picture ghost  路  3Comments

renatorib picture renatorib  路  3Comments

olifante picture olifante  路  3Comments