componentWillUnmount() in ReacJS Class-Based and Functional components

componentWillUnmount() in ReacJS Class-Based and Functional components

For Class-Based components

componentWillUnmount() is used for cleanup tasks just before a component is removed from the DOM. It's particularly useful for cleaning up event listeners, subscriptions, or other resources to prevent memory leaks.

Here's an example demonstrating its usage in a class-based component:

In this example:

  • In componentDidMount(), we set up an interval using setInterval() and store the interval ID in the component's state.
  • In componentWillUnmount(), we clear the interval using clearInterval() to prevent memory leaks when the component is unmounted.

For Functional components

For this we are going to rely on useEffect, exactly on the return function. In this function we will can code logic to handle the componentWillUnmount cycle state

In this functional component example:

  • We use the useEffect() hook with an empty dependency array ([]) to mimic componentDidMount(). This ensures that the effect runs only once after the initial render.
  • Inside the effect, we set up an interval using setInterval() and return a cleanup function that clears the interval using clearInterval() when the component is unmounted.

Both examples achieve the same result: cleaning up resources when the component is about to be removed from the DOM. However, the functional component with hooks offers a more concise and readable syntax.