Functional Components

  • Functional components are basic JavaScript functions. These are typically arrow functions but can also be created with the regular function keyword
  • There is no render method used in functional components. Instead, the JSX is returned from the function
  • These are mainly responsible for UI and are typically presentational only (For example, a Button component)
  • Functional components can accept and use props
  • Functional components can have state by using hooks

    const GreetingComponent = props => (
      <div>
        <h1>Hello, {props.name}</h1>
      </div>
    );

    export default GreetingComponent;
    

Class component

  • Class components make use of ES6 class and extend the Component class in React.
  • React lifecycle methods can be used inside class components (for example, componentDidMount).
  • You pass props down to class components and access them with this.props

    class GreetingComponent extends Component {
      constructor(props){
        super(props);
      }

      render() {
        return (
          <div>
            <h1>Hello {props.name}</h1>
          </div>
        );
      }
    }

    export default Person;

Which to use?

For most use cases, using functional components is the best approach. Since the introduction of React Hooks which gives functional components the ability to have state, there is little use for class components. Learn in more detail how to create a functional component in React here

This is part of the React bite-size series of posts. Check out the rest here!