bluenote10
bluenote10

Reputation: 26710

Is it safe to rely on React reusing existing DOM element (e.g. for CSS transitions)?

Consider the following small CSS transition example:

function CssTransitionExample() {
  const [large, setLarge] = useState(false);

  const commonStyle = { border: "1px solid #444", transition: "all 1s" };

  return (
    <div>
      <button onClick={() => setLarge(!large)}>toggle</button>
      {large ? (
        <div
          style={{
            ...commonStyle,
            width: "300px",
            height: "300px",
          }}
        />
      ) : (
        <div
          style={{
            ...commonStyle,
            width: "100px",
            height: "100px",
          }}
        />
      )}
    </div>
  );
}

The code works as expected: Clicking the button toggles the visible square between its small and large states with a nice CSS transition.

The reason it works is because React actually re-uses the existing <div /> in the DOM. If React would instead remove the old <div /> from the DOM first, followed by attaching a fresh <div /> the CSS transition wouldn't work.

The question is: Is it safe to use such an approach for transitions, i.e., do the React specs indicate that it will keep this behavior in the foreseeable future, or is the approach relying too much on an implementation detail of React?

Upvotes: 1

Views: 30

Answers (1)

Anya
Anya

Reputation: 1418

Considering the way React updates and re-renders its virtual dom, I'd say it would be a safe approach; but I wouldn't call it the better one.

If you just want to change the inline styles, why don't you use another approach, such as ternary conditionals on the style object? Something like this:

  return (
    <div>
      <button onClick={() => setLarge(!large)}>toggle</button>
        <div
          style={{
            ...commonStyle,
            width: large ? "300px" : "100px",
            height: large ? "300px" : "100px",
          }}
        />
      )}
    </div>
  );

Upvotes: 1

Related Questions