Search code examples
reactjsradium

Radium with useState makes Invalid hook call


I use Radium and it works, but when I add useState I get this error: Invalid hook call. Hooks can only be called inside of the body of a function component...

Can I repair it without changing function to class?

import React, {useState} from 'react';
import Radium, {StyleRoot} from 'radium';

const App = ()=>{
  const [tab, updateTab] = useState([1, 2, 3]);

  return (
    <StyleRoot>
      <div className='App'>

      </div>
    </StyleRoot>
  )
};

export default Radium(App);

Solution

  • Can I repair it without changing function to class?

    Yes. To make this work, extract a component to put your hooks.

    const Root = () => {
      const [tab, updateTab] = useState([1, 2, 3]);
      return <div className="App" />;
    }
    
    const App = () => {
      return (
        <StyleRoot>
          <Root />
        </StyleRoot>
      )
    };
    
    export default Radium(App);