Conteúdo do curso
React.js: Understand and Apply the Lifecycle
Sobre a Aula

Comparison between Hooks and lifecycle methods in class components

Lifecycle methods and hooks are essential for managing the behavior of components in React. Each has its advantages and specific uses.

Class Components

In class components, we use lifecycle methods to control different phases of the component. Here are some main methods:

  • componentDidMount(): Executed after the component is mounted.
  • componentDidUpdate(): Executed after an update.
  • componentWillUnmount(): Executed before the component is unmounted.

See a basic example:

class MyComponent extends React.Component {
  componentDidMount() {
    // Executes when the component mounts
    console.log('Component mounted');
  }

  componentDidUpdate(prevProps) {
    // Executes after an update
    console.log('Component updated');
  }

  componentWillUnmount() {
    // Executes before the component unmounts
    console.log('Component unmounted');
  }

  render() {
    return <div>Hello, world!</div>;
  }
}

Hooks

With hooks, we manage the lifecycle in functional components. The main hooks used for this purpose are:

  • useEffect(): Executes side effects. It combines componentDidMount, componentDidUpdate, and componentWillUnmount.

Here is an example:

import React, { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // Executes when the component mounts
    console.log('Component mounted');

    // Executes when the component unmounts
    return () => {
      console.log('Component unmounted');
    };
  }, []); // Empty array means it only executes on mount and unmount

  return <div>Hello, world!</div>;
}

Key Differences

  1. Simplicity: Hooks allow using functions instead of classes, resulting in cleaner code.
  2. Logic Reuse: With hooks, we can extract and reuse state logic more easily.
  3. Conciseness: Hooks combine multiple lifecycle methods into a single function (useEffect).

Similarities

  1. Functionality: Both manage states and side effects.
  2. Context: Both have access to the component’s context.

Conclusion

Class components use lifecycle methods, while functional components use hooks. Hooks are more modern and promote more concise and reusable code. However, understanding both is crucial for working effectively with React.

Entrar na conversa
Rolar para cima