How to call useEffect React Hook on a component mount and unmount

Article autor
September 9, 2025
How to call useEffect React Hook on a component mount and unmount
Elixir Newsletter
Join Elixir newsletter

Subscribe to receive Elixir news to your inbox every two weeks.

Oops! Something went wrong while submitting the form.

Table of contents

With pure function React Components you're not allowed to use lifecycle methods like componentDidMount or componentWillUnmount.

These can be replaced with proper use of useEffect hook introduced in React version 16.8.

Here is the code that will run exactly once when a component is mounted and exactly once when it's supposed to be unmounted:

import { useEffect } from "React";

const ExampleComponent = () => {
  useEffect(() => {
    // Here goes the code you wish to run on mount

    return () => {
      // Here goes the code you wish to run on unmount
    }
  }, []);

  ...
}

It's crucial to pass an empty array as the second argument of useEffect function call. If you omit it or pass dependencies inside of array it won't work as intended.

Related posts

Dive deeper into this topic with these related posts

No items found.

You might also like

Discover more content from this category

How to process Phoenix conn after render before it is sent as a response

There are a bunch of operations you may want to perform before the rendered response in conn is sent to the client, such as minification. In this post I'll show you how to do it easily.

Treating warnings as errors in Elixir's mix compile

Warnings in Elixir are usually an important sign of a problem in the codebase. There is an easy way to make them gone.

How to set default value in JavaScript’s Destructuring

Did you know that it's possible to set default value in Javascript object destructuring?