Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React vs Redux props on the 'constructor' and 'super'

Tags:

reactjs

redux

Why do I have 'props' passed as parameter in ReactJS and it doesn't happen when I use ReduxJS?

for example:

React app:

 constructor(props){
    super(props);
    this.state = {
      memeLimit: 10
    }
 }

Redux app:

constructor(){
    super();
    this.state = {
      memeLimit: 10
    }
 }

Thank you

like image 770
claudiopb Avatar asked May 19 '18 21:05

claudiopb


People also ask

Why we use constructor props and super props in React?

Super(): It is used to call the constructor of its parent class. This is required when we need to access some variables of its parent class. Props: It is a special keyword that is used in react stands for properties. Used for passing data from one component to another.

What is the purpose of super props used in constructor of a React class component?

props in a Constructor function. In fact, what the super() function does is, calls the constructor of the parent class. Syntax: There's nothing complex in using super(props), we just have to call super(props) in the constructor method of our child class component, like so: class Checkbox extends React.

Does Redux solve prop drilling?

Both Redux and React's Context API deal with "prop drilling". That said, they both allow you to pass data without having to pass the props through multiple layers of components.

Is it necessary to use constructor in React?

If you don't initialize state and you don't bind methods, you don't need to implement a constructor for your React component. The constructor for a React component is called before it is mounted. When implementing the constructor for a React. Component subclass, you should call super(props) before any other statement.


1 Answers

The reason to use super(props); is to be able to use this.props inside the constructor, otherwise you don't need super(props);

For example

 constructor(props){
    super(props);
    this.state = {
      memeLimit: this.props.memeLimit // Here you can use this.props
    }
 }

This is equivalent to

 constructor(props){
    super();
    this.state = {
      memeLimit: props.memeLimit // Here you cannot use this.props
    }
 }

This not really related to Redux Vs React

You can check this for more details: What's the difference between "super()" and "super(props)" in React when using es6 classes?

like image 164
Anas Avatar answered Sep 30 '22 04:09

Anas