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:

  1. FC is a component is a function that returns JSX code
  2. FC receives input as props and output is JSX
  3. The reason why in the earlier versions of React we couldn't use Functional components is because it couldn't support state
  4. After version 16.8 with the introduction of hooks, we can now use Functional components which supports states
  5. Less coding
  6. Consuming props and state in FC
    • using state in FC - can be done easily with useState hook const [name, setName] = useState('');

image

  • 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

  1. CBC need to extends Component and need to import { Component } from 'react'
  2. CBC need to have render() function and inside that return { JSX code
  3. Previously ONLY CBC could have state in a component
  4. More coding in CBC
  5. 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

image

  • 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