Skip to content

[bug]: useTransition not working with React 18 #2395

@romain-trotard

Description

@romain-trotard

Which react-spring target are you using?

  • @react-spring/web
  • @react-spring/three
  • @react-spring/native
  • @react-spring/konva
  • @react-spring/zdog

What version of react-spring are you using?

10.0.2

What's Wrong?

Hello :)

With the change made here, the hook useTransition does not work anymore when using React in v18.

If returning null from the transition function we get the error Cannot read properties of null (reading 'ref').

See reproduction: https://codesandbox.io/p/devbox/react-spring-ref-pb-forked-dszjxn?workspaceId=ws_HL6gchWTGZas2nUL51SZeG

Otherwise we get the error Cannot add property ref, object is not extensible

See reproduction: https://codesandbox.io/p/devbox/elated-shamir-kftfgn?workspaceId=ws_HL6gchWTGZas2nUL51SZeG

To Reproduce

  • use React 18
  • use useTransition for example to show/hide a div

For example with the following code:

function Card() {
  const [show, setShow] = useState(false);

  const transition = useTransition(show, {
    config: { duration: 5000 },
    from: { opacity: 0 },
    enter: { opacity: 1 },
    leave: { opacity: 0 },
  });

  return (
    <div>
      <button type="button" onClick={() => setShow(!show)}>
        Show element
      </button>
      {transition(
        (styles, newShow) =>
          newShow && (
            <animated.div styles={styles}>An element to show</animated.div>
          ),
      )}
    </div>
  );
}

I made a codesandbox with the problem https://codesandbox.io/p/devbox/elated-shamir-kftfgn?workspaceId=ws_HL6gchWTGZas2nUL51SZeG

Expected Behaviour

It should not throw an error.

To fix the first issue the condition here https://github.com/pmndrs/react-spring/pull/2373/files#diff-3dce88b788d6e5008705461509e6c3a027695ca9a198d918b9d9c4800d4d2181R441 should be if (isLegacyReact && elem) (and if we want to be 100% as before if (isLegacyReact && elem && elem.type)

For the second issue recreate a new object object from elem?.props works: const props = { ...elem?.props }

Thanks

Link to repo

https://codesandbox.io/p/devbox/elated-shamir-kftfgn?workspaceId=ws_HL6gchWTGZas2nUL51SZeG

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions