Allow state to be an object or an array
See original GitHub issueI would like to propose that React allows state
to be an object or an array (or maybe even a simple value such as number or a string or a boolean). The reason I am proposing this is that I thought it was already possible (I think of setState
sort of like patching a JSON and JSON allows top level arrays and simple values), but I found our the hard way it was not this morning.
I can set the initial state just fine like this:
type MyComponentState = { value: string; }[];
class MyComponent extends Component<{}, MyComponentState> {
public readonly state: MyComponentState = [];
}
However when I issue a state change such as this:
this.setState(state => [ ...state, { value: 'new' } ]);
The state
will then be an object with key 0
, not an array! This is not caught by the React TypeScript typings, nor by React itself (telling me I cannot do this in the constructor nor in setState
as a runtime check - not even in the development bundle, which otherwise checks many things, event things like mounting to body
etc.). So the only way to find out is to wonder why this.state.map
is undefined
in the render
that follows the setState
call merge.
Thanks for considering this!
Issue Analytics
- State:
- Created 5 years ago
- Comments:6 (1 by maintainers)
useState
does everything you want; the state value can be of any type and there’s no automaticObject.assign()
going on behind the scenes.I really hope the existence of Hooks (which were supposed to be just an RFC and testing the waters AFAIK just a few weeks ago [even though they immediately became the part of the documentation…]) will not prevent new development on class based components.
I know in your blog posts you said those are not going anywhere (probably ever), but I also hope they will continue being actively developed.
I am not talking about this issue specifically, IMO it’s a good QoL improvement but not that important. In general though, just because something is easy with hooks shouldn’t IMO mean that we stop to look for ways to make it nice with class components, too. Many people will not learn hooks and many people will not use them out of principle, because not everyone thinks they are a good idea. It would be a mistake for them to “taint” the rest of React if they became and argument againstimprovement to class components in the future.