The issue is not considered a bug by maintainers and has low priority.
The issue reports confusion when using a class as initial state in `useState`, but maintainers consider this expected behavior. The suggested solution would require changes to how React handles initial state or documentation updates, but there's no consensus on whether this is worth addressing.
Using a JavaScript class as initial state in useState throws an error. This is because mountState check if the initial state is a function by typeof initialState === 'function' and classes are technically functions. However since ES6+, I feel like most developers don't consider classes functions because of the less prototype-inheritance feel since ES6 and the class keyword.
React version: 17.0.2
initialState argument to useStateCode example:
import { useState } from "react";
import ReactDOM from "react-dom";
class A {}
function App() {
const [cls, setCls] = useState(A);
return <h2>{cls.name}</h2>;
}
ReactDOM.render(<App />, document.body);
TypeError: Cannot call a class as a function
at _classCallCheck (eval at z (eval.js:42), <anonymous>:3:11)
at A (VM302 index.js:19)
at mountState (react-dom.development.js:10436)
at Object.useState (react-dom.development.js:10919)
at useState (react.development.js:954)
at App (VM302 index.js:25)
Alternatively, the error can be TypeError: Class constructor X cannot be invoked without 'new'.
As mentioned in the description above, I would
I guess checking, if the initial state is actually a non-class function, could cause instances of subclasses of functions not to work (depending how the check is done).
Claim this issue to let others know you're working on it. You'll earn 5 points when you complete it!