Differences between Functional Components and Class Components

React components are the building blocks of a React application, defining the UI elements and encapsulating their behavior. Two primary types of components exist in React: class components and functional components. In this blog post, we’ll explore the differences between these two component types, their use cases, and the introduction of hooks, which have brought functional components closer to feature parity with class components.

Choosing Between Functional and Class Components in React

React components come in two flavors: functional and class. Each type has its strengths and use cases. In this blog post, we’ll explore the differences between functional and class components, covering aspects like passing props, handling state, and lifecycle methods.

Functional Components

A functional component is simply a javascript function that accepts data in the form of props and returns the react element

Passing Props in Functional Components

In a functional component, props are passed as parameters to the function:

import React from 'react';

const GreetUser = (props) => {
  return <p>Hello, {props.username}!</p>;
};

Handling State in Functional Components

With the introduction of hooks, functional components can now handle state using useState:

import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
};

Lifecycle Methods in Functional Components

Functional components use the useEffect hook to achieve effects similar to lifecycle methods in class components:

import React, { useEffect } from 'react';

const LifecycleExample = () => {
  useEffect(() => {
    console.log('Component is mounted!');

    // Cleanup function (equivalent to componentWillUnmount)
    return () => {
      console.log('Component is about to be removed!');
    };
  }, []);

  useEffect(() => {
    console.log('Component is updated!');
  });

  return <p>Check the console for lifecycle messages.</p>;
};

Class Components:

The class component, on the other hand, is formed with the class keyword and extends React. Component to create the class as a react component

Passing Props in Class Components

In a class component, props are accessed using this.props:

import React, { Component } from 'react';

class GreetUser extends Component {
  render() {
    return <p>Hello, {this.props.username}!</p>;
  }
}

Handling State in Class Components

State in class components is managed using the setState method:

import React, { Component } from 'react';

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.increment}>Increment</button>
      </div>
    );
  }
}

Lifecycle Methods in Class Components

Class components have explicit lifecycle methods:

import React, { Component } from 'react';

class LifecycleExample extends Component {
  componentDidMount() {
    console.log('Component is mounted!');
  }

  componentWillUnmount() {
    console.log('Component is about to be removed!');
  }

  render() {
    return <p>Check the console for lifecycle messages.</p>;
  }
}

When to Choose Which?

  • Functional Components: Use these for simpler components, especially when dealing with hooks for state and effects.

  • Class Components:- Use the class component when the component needs to maintain its state, the component is re-rendering too much, and you need to control the life cycle event.

Conclusion

Choosing between functional and class components in React depends on your project’s needs and personal preferences. Both have their places, and understanding the strengths of each will make you a more versatile React developer. As you navigate the React landscape, experimenting with both types of components will provide a well-rounded understanding of this powerful library. Happy coding!

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru