1

I was looking at Facebook React Native documentation and I saw super(props) in constructor in State part.

I found that we use super(props) only if we want to access props in constructor.

My question, isn't it unnecessary to use props in here then?

class Blink extends Component {
  constructor(props) {
  super(props);
  this.state = {isShowingText: true};

  // Toggle the state every second
  setInterval(() => {
   this.setState(previousState => {
    return { isShowingText: !previousState.isShowingText };
  });
}, 1000); 
Safa Elmalı
  • 79
  • 1
  • 11
  • as you found *we use super(props) only if we use props in constructor.*, that means in your case its not required :) – Mayank Shukla Jun 11 '18 at 08:04
  • Yeah.But I confused because, even though in the documentation they didn't use props in constructor, they used it in super() :) – Safa Elmalı Jun 11 '18 at 08:08
  • check this https://stackoverflow.com/questions/30571875/whats-the-difference-between-super-and-superprops-in-react-when-using-e?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Shubhanu Sharma Jun 11 '18 at 08:08
  • I already mentioned it in my question :)) – Safa Elmalı Jun 11 '18 at 08:09
  • If you are planning to override constructor then do call `super(props)` for the sake of future compatibillity. Who knows what base component constructor would do to it. But constructor should be kept as simple as possible. So, a better approach would be to move state initialization to class property initializer. And `setInterval` part to component lifecycle methods where it belongs to. For example you need to clear interval when component got unmounted (now you don't) – Yury Tarabanko Jun 11 '18 at 08:29

1 Answers1

1

No it's not necessary.You can have a class component that has only a render in it.

example:

class EventsContainer extends React.Component {
 render() {
 const futurEvents = getFuturEvents(this.props.events);
 const passedEvents = getPassedEvents(this.props.events);

 return this.props.loggedIn
 ? <div>
     <NavbarContainer />
     <Events
       futurEvents={futurEvents}
       passedEvents={passedEvents}
       deleteEventInStateAndDB={this.props.deleteEventInStateAndDB}
     />
   </div>
 : <Redirect push to='/'/>
 }
}
Genia
  • 80
  • 9