React hooks not working when imported from local library

Viewed 3541

I'm using React to import a function with a useState hook and that seems to break it. I have a version of react with hooks:

npm ls react => react@16.10.2
npm ls react-dom => react-dom@16.10.2

I can use components fine. When I include a hooks, I get the "Invalid hook call" screen.

In my library project I have:

/**
 * @class ExampleComponent
 */

import * as React from 'react'

import styles from './styles.css'

export default function ThingyDefault() {
  return <p>hi</p>
}

export type Props = { text: string }

export class ExampleComponent extends React.Component<Props> {
  render() {
    const {
      text
    } = this.props

    return (
      <div className={styles.test}>
        Example Component: {text}
      </div>
    )
  }
}

////////////////// THIS DOESN'T SEEM TO WORK //////////////////
export function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = React.useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

In my project that uses that library:

import React from 'react';
import './App.css';
import ThingyDefault, {ExampleComponent, Example} from 'thingy';

const App: React.FC = () => {
  return (
    <div>
    <ThingyDefault />
    <ExampleComponent text='hello' />

    {/* commenting this component out makes it work */}
    <Example />
    </div>
  );
}

export default App;

What am I doing wrong here?

3 Answers

You are not adhering to the Rules of Hooks, specifically in your case, calling a hook from a standard javascript function.

Only Call Hooks from React Functions Don’t call Hooks from regular JavaScript functions. Instead, you can:

✅ Call Hooks from React function components. ✅ Call Hooks from custom Hooks (we’ll learn about them on the next page). By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code.

Since it seems to be a import/export issue, try changing your export to this:

const Example = () => {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = React.useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
export { Example };

You're not doing anything wrong there. It should work as intended. Check the example Stackblitz here, with the same version of React that you have.

I might re-check the app for any duplicate dependencies messing up the functionality of the hooks. Especially, it's unable to determine that your function Example(), is indeed a functional component.

Related