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.
Elixir Newsletter
Expand your skills

Download free e-books, watch expert tech talks, and explore open-source projects. Everything you need to grow as a developer - completely free.

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

Skip file changes tracking in git

So, you’re changing this one file for local development purposes only. Maybe it’s config, maybe some source file, but one thing is certain - you don’t want those changes to be committed. And what’s worse, .gitignore doesn’t work.

Implicit try in Elixir

In the world of Elixir programming, there are numerous features and syntactic constructs that contribute to the language's elegance and expressiveness. One such hidden gem is the concept of "implicit try".

How to safely handle related database operations with Ecto Multi

Sometimes you need to do some database operations at once. A simple example: User-A transfers money to User-B. Updating just one balance at the time creates a risk of data desynchronization. What if the first DB operation goes well but updating the second user’s data fails? Sounds like a hard to catch vulnerability.