Daniel San
Daniel San

Reputation: 2036

What is the appropiate way to define a react component class without state?

I'm wondering if the recommended way to define a react class component with typescript is using a void as state type:

class MyComponent extends React.Component<any, void> {
   constructor(props) {
      super(props);
      // The typescript compiler won't allow this using void type
      // this.state = {...}
   [...]
}

Do you know a recommended or better way?

Note: the component must be a class because I will need the lifecycle methods

Upvotes: 0

Views: 153

Answers (1)

Amid
Amid

Reputation: 22382

Its perfectly legal to use void as state type. I have not seen any "official" recommendations for stateless components based on classes, but (if this will make you feel safer) this approach is used by some not so small projects.

You can use {} instead of void but this will not protect you from assigning something to state.

It is also possible to specify never and it seems to give the same results as void.

Upvotes: 1

Related Questions