Warning: Prop src did not match. Server. And images aren't updated when shuffling an array before rendering it
Create an array outside of a component and shuffle it before rendering (When runs on server only)
Shouldn't throw client and server mismatch and update the images correctly
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]);
}
No
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
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