React: [lint] False positive when using hooks inside static component

Created on 13 Oct 2019  路  6Comments  路  Source: facebook/react

Do you want to request a feature or report a bug?
BUG

What is the current behavior?

Error reported when using hooks inside component as a static property:

https://codesandbox.io/s/suspicious-darwin-9qh7y?fontsize=14

React Hook "useState" is called in function "Foo.Bar" which is neither a React function component or a custom React Hook function.

What is the expected behavior?

No error.

Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?

React 16.10.1

Stale

Most helpful comment

If you write like this, then no warning should appear.
Your Bar function is anonymous.

import React from "react";

const Foo = () => <div>Foo</div>;
const Bar = () => {
  const [counter, setCounter] = React.useState(0);
  return (
    <button
      onClick={() => {
        setCounter(s => s + 1);
      }}
    >
      {counter}
    </button>
  );
};
Foo.Bar = Bar;
export default Foo;

All 6 comments

Updated example to not have other errors:
https://codesandbox.io/s/vibrant-swirles-onoee

import React from "react";
import { useState } from "react";
import ReactDOM from "react-dom";

const Foo = () => <div />;
Foo.Bar = () => {
  const [counter, setCounter] = useState(0);
  return <div onClick={() => setCounter(c => c + 1)}>{counter}</div>;
};

const rootElement = document.getElementById("root");
ReactDOM.render(<Foo.Bar />, rootElement);

To be Elaborate , the useState works even when the component is neither a React Component or Function.
I tried to look into the issue with the latest version of React

"react": "^16.10.2",
"react-dom": "^16.10.2",
"react-scripts": "3.2.0"

but i am not able to compile and got the below error, with the code for onclick in div tag too
Screenshot_1258

@abrahamwilliam export default Foo;

If you write like this, then no warning should appear.
Your Bar function is anonymous.

import React from "react";

const Foo = () => <div>Foo</div>;
const Bar = () => {
  const [counter, setCounter] = React.useState(0);
  return (
    <button
      onClick={() => {
        setCounter(s => s + 1);
      }}
    >
      {counter}
    </button>
  );
};
Foo.Bar = Bar;
export default Foo;

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contribution.

Closing this issue after a prolonged period of inactivity. If this issue is still present in the latest release, please create a new issue with up-to-date information. Thank you!

Was this page helpful?
0 / 5 - 0 ratings