Class based vs Function components study - florypaul/ReactJS GitHub Wiki
Why use Functional components instead of Class components -
https://www.youtube.com/watch?v=yc6elaGOoGQ
Functional Component:
- FC is a component is a function that returns JSX code
- FC receives input as props and output is JSX
- The reason why in the earlier versions of React we couldn't use Functional components is because it couldn't support state
- After version 16.8 with the introduction of hooks, we can now use Functional components which supports states
- Less coding
- Consuming props and state in FC
- using state in FC - can be done easily with useState hook const [name, setName] = useState('');
- props in FC - we can pass props as an argument to the function and use it as props.variablename function User(props){ props.name}
- In FC we can right away destructure the props in the arguments function User({name}){ {name}}
Class based components
- CBC need to extends Component and need to import { Component } from 'react'
- CBC need to have render() function and inside that return { JSX code
- Previously ONLY CBC could have state in a component
- More coding in CBC
- Consuming props and state in CBC
- Using state in CBC - we need to use constructor and super function
- super will call the constructor of parent which is extended which is Component in our case
- We have to pass props in constructor() and pass props even to super() the parent's constructor which takes these props
- we have to use props in CDC with this keyword this.props.name