Skip to content
Middle+7 views

In the React example, the counter updates when the button is clicked. Make the value reappear with the original fade animation on every update, using only React, without CSS animations or vanilla JavaScript.

Practice

AI answer

To trigger the appearance again, you can remount the element with a new key. For example, give it an initial opacity and change it after mounting. The example below uses a CSS transition rather than a CSS animation; React manages the state and retriggering.

import { useEffect, useState } from "react";

function FadeValue({ value }) {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    setVisible(true);
  }, []);

  return (
    <span
      style={{
        opacity: visible ? 1 : 0,
        transition: "opacity 400ms ease",
      }}
    >
      {value}
    </span>
  );
}

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <>
      <FadeValue key={count} value={count} />
      <button onClick={() => setCount((current) => current + 1)}>
        Increase
      </button>
    </>
  );
}

Each time count changes, the key changes, React creates a new FadeValue, and the transition starts again. If the restriction also rules out CSS transitions, React alone is not enough: React updates the interface but does not perform visual interpolation on its own.