'cannot use react-spring (Uncaught Invariant Violation: Invalid hook call)

import logo from "./logo.svg";
import "./App.css";
import { useSpring, animated } from "react-spring";
function App() {
  const props = useSpring({ to: { opacity: 1 }, from: { opacity: 0 } });
  return <animated.div style={props}>I will fade in</animated.div>;
}

export default App;

From the code above, I am trying to use the useSpring hook from react-spring library that i just downloaded using npm i react-spring but it seems to be throwing out this error:

Error image

I tried using other hooks from 'react' and it worked (useState, useEffect). it is only the hooks from 'react-spring' that doesn't work so I can't figure out why this is happening.



Solution 1:[1]

I had the same issue. The versions of my packages were:

"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-spring": "^9.4.4",

Upgrading react-spring's version to 9.4.5-beta.1 solved the issue for me.

"react-spring": "^9.4.5-beta.1",

You can also try downgrading react and react DOM. For e.g. you could downgrade both to 17.0.2. Keep in mind you would have to change your index.js to use ReactDOM.render instead of ReactDOM.createRoot:

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kaif Kutchwala