-1

Im really having trouble understanding the state in React. Whats the differences between,

This:

class Todo extends ... {
constructor (){
 super()
 this.state = { ... }
 }
}

And This:

class Todo extends ... {
 state = { ... }
}

And Im also confused and dumb understanding why theyre putting sometime a function inside state.

const [ user, setUser] = useState(() => ...)

I cant find any resources on differentiating those topics. I hope you can help me explained how and why is that. Ive read blogs about React but they didnt mention those things above.

Zowy
  • 41
  • 7
  • `useState` is only available in function components (the ones that aren't classes). the other two are just two methods of doing the same thing for Class components. One the state is initialised with the object, the other in the constructor allows you to set the state based off the initial props passed to the component. – Jacob Smit Jul 27 '20 at 09:24
  • [What is the difference between using constructor vs state = {} to declare state in react component?](https://stackoverflow.com/questions/45451141/what-is-the-difference-between-using-constructor-vs-state-to-declare-state) and I suspect you've seen `setUser(() => ...)` instead of `useState(() => ...)`. – Guy Incognito Jul 27 '20 at 09:26
  • No, the useState(() =>) is different. Ive seen it in yt hes using it. And I think its valid but I dont know howndoes it works. – Zowy Jul 27 '20 at 09:39
  • Jacob Smith, so the state with constructor is for only passing a state to components but with a props in it? – Zowy Jul 27 '20 at 09:40

1 Answers1

0

Since Babel is adding constructor behind scenes for you, there is no need to declare it. You can just omit it and define your state like in the second example, in the end result will be exactly the same.

Kary
  • 229
  • 1
  • 8
  • Thank you sir! So the, constructor (props){ super(props) this.state = { ... } use only in the components when your passing a state on it right? – Zowy Jul 27 '20 at 09:35
  • Nope, if you need to pass some date use props. Passing a state is considered bad practice, so there is really no reason to declare it inside the constructor. – Kary Jul 27 '20 at 09:49
  • Yeah yeah. Im using redux or context instead thanks for enlighting me sir! – Zowy Jul 27 '20 at 10:04