, but listens for successful load events, and
+ * fades from the previous image to the new image once it loads.
+ *
+ * We treat `src` as a unique key representing the image's identity, but we
+ * also carry along the rest of the props during the fade, like `srcSet` and
+ * `className`.
+ */
+function CrossFadeImage(incomingImageProps) {
+ const [prevImageProps, setPrevImageProps] = React.useState(null);
+ const [currentImageProps, setCurrentImageProps] = React.useState(null);
+
+ const incomingImageIsCurrentImage =
+ incomingImageProps.src === currentImageProps?.src;
+
+ const onLoadNextImage = () => {
+ setPrevImageProps(currentImageProps);
+ setCurrentImageProps(incomingImageProps);
+ };
+
+ // The main trick to this component is using React's `key` feature! When
+ // diffing the rendered tree, if React sees two nodes with the same `key`, it
+ // treats them as the same node and makes the prop changes to match.
+ //
+ // We usually use this in `.map`, to make sure that adds/removes in a list
+ // don't cause our children to shift around and swap their React state or DOM
+ // nodes with each other.
+ //
+ // But here, we use `key` to get React to transition the same