Each time I'm dealing with internal component state in React I must first define empty object for state property or else I will get runtime errors throwing this.state is undefined
If I was about to do this:
render() {
const { someProperty } = this.state;
render <div>{someProperty}</div>
}
I'm gonna get error.
But the cure is quite simple:
constructor(props) {
super(props);
this.state = {};
}
However this is very annoying to do this over and over for each component that I create.
Is it somehow possible to force react add initial state as an empty object globally as to avoid all the boilerplate for empty state definition?
P.s. (maybe rhetorical question) Why isn't this done in the same React core?
To type the useState hook with an empty object initial value in React, use the hook's generic, e.g. const [employee, setEmployee] = useState<{[key: string]: any}>({}) . The state variable will be typed as an object with dynamic properties and values.
There are two ways to initialize state in a React component: inside the constructor, and directly inside the class.
Where the props are used to set the initial state of the Component is a general anti-pattern of React. This implies that the state of the component is tied to the props of the component. The issue with doing this is that the constructor is only ever called once in the life cycle of the component.
Is it somehow possible to force react add initial state as an empty object globally as to avoid all the boilerplate for empty state definition?
You could create your own »component base class« extending from React.Component
which implements this and then derive all of your components from this class instead.
import { React } from 'react';
class StatefulComponent extends React.Component {
constructor(...args) {
super(...args);
this.state = {};
}
}
export default StatefulComponent;
.
class MyComponent extends StatefulComponent {
render() {
const { something } = this.state;
return (<div>Hello, {something}</div>);
}
}
(Live Demo)
Typically extending components in React is discouraged as it's not idiomatic; and really no harm in adding this.state = {}
in (every) component that requires state. But if you want to go that route, you can do it.
P.s. (maybe rhetorical question) Why isn't this done in the same React core?
Because many (or most) components don't require state, thus you'd be allocating wasted memory. This has been discussed in react#1851:
syranide: For components that don't need state (which could easily be the majority), avoiding an allocation is a win.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With