Fix homepage image hydration errors #1605
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What are the relevant tickets?
Fixes: https://github.com/mitodl/hq/issues/5416
Description (What does it do?)
We select images at random on the homepage for the hero and testimonial images. We also shuffle the testimonials. The issue is that Next.js performs the render on the server and expects the React tree not to shift when it hydrates on the client, or it logs a hydration error to console. Some information here: https://nextjs.org/docs/messages/react-hydration-error. The user will also see the flash of server rendered content.
This change uses
useStateanduseEffectto force the randomize on the client and only once.How can this be tested?
In dev mode (
docker compose uporyarn workspace main dev), the homepage should display the hero and testimonial images at random after each refresh and should load without any console errors around hydration or image warnings.Additional Context
With our current approach we do need the selection to happen client side, given that the server rendered content will be cached on the CDN. This does mean the page loads initially with no image while hydrating, though in the case of the hero image, the container bounds are preserved to prevent any layout shift.