You cannot use any of the existing lifecycle methods (componentDidMount, componentDidUpdate, componentWillUnmount etc.) in a hook. They can only be used in class components. And with Hooks you can only use in functional components. The line below comes from the React doc:

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

suggest is, you can mimic these lifecycle method from class component in a functional components.

Code inside componentDidMount run once when the component is mounted. useEffect hook equivalent for this behaviour is

useEffect(() => {
  // Your code here
}, []);

Notice the second parameter here (empty array). This will run only once.

Without the second parameter the useEffect hook will be called on every render of the component which can be dangerous.

useEffect(() => {
  // Your code here
});

componentWillUnmount is use for cleanup (like removing event listeners, cancel the timer etc). Say you are adding a event listener in componentDidMount and removing it in componentWillUnmount as below.

const mouseMoveHandler = () => {}

componentDidMount() {
  window.addEventListener('mousemove', mouseMoveHandler)
}

componentWillUnmount() {
  window.removeEventListener('mousemove', mouseMoveHandler)
}

Hook equivalent of above code will be as follows:

useEffect(() => {
  const mouseMoveHandler = () => {}

  window.addEventListener('mousemove', mouseMoveHandler);

  // returned function will be called on component unmount 
  return () => {
    window.removeEventListener('mousemove', mouseMoveHandler)
  }
}, [])
Answer from Bhaskar Gyan Vardhan on Stack Overflow
Top answer
1 of 16
757

You cannot use any of the existing lifecycle methods (componentDidMount, componentDidUpdate, componentWillUnmount etc.) in a hook. They can only be used in class components. And with Hooks you can only use in functional components. The line below comes from the React doc:

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

suggest is, you can mimic these lifecycle method from class component in a functional components.

Code inside componentDidMount run once when the component is mounted. useEffect hook equivalent for this behaviour is

useEffect(() => {
  // Your code here
}, []);

Notice the second parameter here (empty array). This will run only once.

Without the second parameter the useEffect hook will be called on every render of the component which can be dangerous.

useEffect(() => {
  // Your code here
});

componentWillUnmount is use for cleanup (like removing event listeners, cancel the timer etc). Say you are adding a event listener in componentDidMount and removing it in componentWillUnmount as below.

const mouseMoveHandler = () => {}

componentDidMount() {
  window.addEventListener('mousemove', mouseMoveHandler)
}

componentWillUnmount() {
  window.removeEventListener('mousemove', mouseMoveHandler)
}

Hook equivalent of above code will be as follows:

useEffect(() => {
  const mouseMoveHandler = () => {}

  window.addEventListener('mousemove', mouseMoveHandler);

  // returned function will be called on component unmount 
  return () => {
    window.removeEventListener('mousemove', mouseMoveHandler)
  }
}, [])
2 of 16
255

useComponentWillMount hook

const useComponentWillMount = (cb) => {
    const willMount = useRef(true)

    if (willMount.current) cb()

    willMount.current = false
}

This hook could be a saver when there is an issue of sequence (such as running before another script). If that isn't the case, use useComnponentDidMount which is more aligned with React hooks paradigm.

useComponentDidMount hook

const useComponentDidMount = cb => useEffect(cb, []);

If you know your effect should only run once at the beginning use this solution. It will run only once after component has mounted.

useEffect paradigm

Class components have lifecycle methods which are defined as points in the timeline of the component. Hooks don't follow this paradigm. Instead effects should be structured by their content.

function Post({postID}){
  const [post, setPost] = useState({})

  useEffect(()=>{
    fetchPosts(postID).then(
      (postObject) => setPost(postObject)
    )
  }, [postID])

  ...
}

In the example above the effect deals with fetching the content of a post. Instead of a certain point in time it has a value it is dependent on - postID. Every time postID gets a new value (including initialization) it will rerun.

Component Will Mount discussion

In class components componentWillMount is considered legacy (source 1, source2). It's legacy since it might run more than once, and there is an alternative - using the constructor. Those considerations aren't relevant for a functional component.

Top answer
1 of 3
19

There are a couple of things there. First, to fix the code, you could update your useEffect to this:

useEffect(() => {
    messagesRef.on('child added', snapshot => {
    const message = snapshot.val();
    message.key = snapshot.key;

    setMessages(messages.concat(message)); // See Note 1
}, []); // See Note 2

Note 1

The setMessages line is how you update your state. useState is a little bit different from the "old" setState in a sense that will completely replace the state value. React documentation says:

This is because when we update a state variable, we replace its value. This is different from this.setState in a class, which merges the updated fields into the object.

Note 2

React Hooks changes the way we build apps and it is not a real "translation" from the old lifecycles.

The empty brackets ([]) in the last line, will make your code "similar" to componentDidMount, but most importantly, will make your effect run only once.

Dan Abramov said (removed some of the original text):

While you can useEffect(fn, []), it’s not an exact equivalent. Unlike componentDidMount, it will capture props and state. So even inside the callbacks, you’ll see the initial props and state. (...) Keep in mind that the mental model for effects is different from componentDidMount and other lifecycles, and trying to find their exact equivalents may confuse you more than help. To get productive, you need to “think in effects”, and their mental model is closer to implementing synchronization than to responding to lifecycle events.

Full article about useEffect here.

2 of 3
1

You tried to declare the state again instead of using the state updater

useEffect(() => {
  messagesRef.on('child added', snapshot => {
    const message = snapshot.val();
    message.key = snapshot.key;
    // setMessages is the state updater for messages
    // instead of an object with messages: messagesArray
    // just save it as an array the name is already messages
    setMessages([...messages, message]);
  });
// useEffect takes an array as second argument with the dependencies
// of the effect, if one of the dependencies changes the effect will rerun
// provide an empty array if you want to run this effect only on mount
}, []);
Discussions

componentWillUnmount with React useEffect hook
How can the useEffect hook (or any other hook for that matter) be used to replicate componentWillUnmount? In a traditional class component I would do something like this: class Effect extends React. More on stackoverflow.com
🌐 stackoverflow.com
useEffect as componentWillUnmount - javascript
My solution was to use to use a useEffect with a cleanup function but despite it 'appearing' to work it failed code review and I can't seem to find a better solution. More on stackoverflow.com
🌐 stackoverflow.com
Does useEffect completely replace mounting lifecycle ?
Actually useEffect and hooks itself are meant to avoid bad practices in React and it does that by changing the API design and forcing the developer to focus only on the concept of side effects, not exactly lifecycles. So yeah it's completely possible to use only useEffect instead of mounting lifecycle. More on reddit.com
🌐 r/reactjs
43
121
May 15, 2022
is useEffect a replacement for componentDidMount ?
They are not the same but can be used to accomplish some of the same tasks. The biggest difference going from class-based components to functional components is that the component doesn't have a "lifecycle" anymore. React just runs the render function every time the component potentially needs to be updated, and this means you have to think about the components a bit differently. Article about the changes here: https://reacttraining.com/blog/useEffect-is-not-the-new-componentDidMount/ More on reddit.com
🌐 r/reactjs
4
5
October 19, 2022
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-simulate-componentdidmount-with-useeffect
How to simulate componentDidMount with useEffect? | GeeksforGeeks
April 28, 2025 - React will run the effect after ... componentWillMount() method allows us to execute the React code synchronously when the component gets loaded or mounted in the DOM (Document Object Model)....
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-use-componentwillmount-in-react-hooks
How to use componentWillMount() in React Hooks? | GeeksforGeeks
July 6, 2023 - ComponentWillMount() will go to be deprecated in future releases of React as per this issue. It is suggested to use ComponentDidMount() or useEffect hook as its alternative but you can still use ComponentWillMount() by calling it as UNSAFE_ComponentWillMount().
🌐
Robert Marshall
robertmarshall.dev › home › blog › how to use componentwillunmount in functional components in react
How to use componentWillUnmount in Functional Components in React | Rob Marshall
November 28, 2022 - If we pass an empty array as the second argument, it tells the useEffect function to fire on component render (componentWillMount).
🌐
DEV Community
dev.to › video › the-equivalent-of-componentwillmount-using-react-hooks-11em
The equivalent of componentWillMount using React hooks - DEV Community
December 9, 2022 - componentWillMount is deprecated (1, 2, 3), and that the suggested replacement is executing code in the constructor
🌐
HackerNoon
hackernoon.com › how-to-use-componentwillmount-with-functional-components-in-react-fc143u9d
How to use componentWillMount with Functional Components in React | HackerNoon
August 10, 2020 - Functional components are far more efficient than class based components. Less code is needed to be written to achieve the same goal.
Find elsewhere
🌐
LogRocket
blog.logrocket.com › home › using react’s useeffect hook with lifecycle methods
Using React’s useEffect Hook with lifecycle methods - LogRocket Blog
June 4, 2024 - Editor’s Note: This post was updated on 17 March 2022 to update any outdated information as well as update the Using componentDidMount in functional components with useEffect section and the Updating phase with shouldComponentUpdate and componentDidUpdate section.
🌐
Reacttraining
reacttraining.com › blog › useEffect-is-not-the-new-componentDidMount
useEffect(fn, []) is not the new componentDidMount()
January 31, 2020 - When developers start learning hooks having come from classes, they tend to think "I need to run some code once when we mount, like how componentDidMount() works. Ah, I see that useEffect with an empty dependency array does just that.
🌐
Medium
singhprince0088.medium.com › useeffect-vs-component-lifecycle-methods-e1ce3eaa63b8
UseEffect( ) Vs Component Lifecycle Methods. | by Prince Singh | Medium
August 13, 2021 - As we knew we should not use directly component lifecycle methods in functional components like componentDidMount( ), componentDidUpdate( ), componentWillMount(). So we can use the useEffect( ) hook instead of these methods.
🌐
Ibrahima-ndaw
ibrahima-ndaw.com › blog › replace-component-lifecycle-with-useeffect
How to replace Component lifecycle with useEffect hook in React?
If we don't pass an empty array to useEffect, it will run on every change. Therefore, we must give as second argument an empty array to mimic the componentDidMount behavior.
🌐
React
react.dev › reference › react › Component
Component – React
For many use cases, defining componentDidMount, componentDidUpdate, and componentWillUnmount together in class components is equivalent to calling useEffect in function components. In the rare cases where it’s important for the code to run before browser paint, useLayoutEffect is a closer match. See how to migrate. This API has been renamed from componentWillMount to UNSAFE_componentWillMount.
🌐
DEV Community
dev.to › trentyang › replace-lifecycle-with-hooks-in-react-3d4n
React Hooks Componentdidmount: Replace lifecycle with hooks in React - DEV Community
January 6, 2019 - There is not a straight forward implementation in hooks to replace componentDidUpdate. The useEffect function can be used to trigger callbacks after every render of the component including after component mounts and component updates.
Top answer
1 of 2
2

React doesn't remember isDropdownMounted variable. It will be recreated on each render. It will be better to use useRef hook to set value in useEffect and remember it on the next render.

const isDropdownMounted = useRef(null);

useEffect(() => {
    isDropdownMounted.current = true;

    return function cleanup() {
      isDropdownMounted.current = false;
    };
  }, []);
2 of 2
2

useEffect lets you return a cleanup function that will run whenever your component unmounts.

NOTE: It will also run whenever something in the dependency array of the useEffect changes. It assures you that you'll always get a "fresh" effect.

React docs on useEffect with cleanup.

Here is the example they use:

Using classes:

componentDidMount() {
    ChatAPI.subscribeToFriendStatus(
      this.props.friend.id,
      this.handleStatusChange
    );
  }

componentWillUnmount() {
  ChatAPI.unsubscribeFromFriendStatus(
    this.props.friend.id,
    this.handleStatusChange
  );
}

Using hooks:

useEffect(() => {
  function handleStatusChange(status) {
    setIsOnline(status.isOnline);
  }
  ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
  // Specify how to clean up after this effect:
  return function cleanup() {
    ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
  };
});

Here is a working example:

function App() {

  const [boolean,setBoolean] = React.useState(true);
  
  const toggleBoolean = () => setBoolean((prevState) => !prevState);

  return(
    <div>
     { boolean ?
         <Component1/>
       : <Component2/>
     }
       <button onClick={toggleBoolean}>Toggle</button>
     </div>
  );
}

function Component1() {

  React.useEffect(() => {
    console.log("Component1 has mounted...");
    return () => { console.log("Component1 has unmounted...")};
  },[]);

  return(
    <div>Component1</div>
  );
}

function Component2() {
  return(
    <div>Component2</div>
  );
}

ReactDOM.render(<App/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>

🌐
Curiosum
curiosum.com › home › blog › today i learned › how to call useeffect react hook on a component mount and unmount
React useEffect hook on a component mount and unmount | Curiosum
December 16, 2025 - 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 } }, []); ...
🌐
Medium
shailendrakanherkar.medium.com › understanding-gotchas-with-un-mounting-using-useeffect-hook-react-b29c3f100ba6
Understanding gotchas with un-mounting using useEffect hook— React | by Shailendra Kanherkar | Medium
May 19, 2021 - Conclusion If we have a dependency array provided as dependency to useEffect then in that case useEffect will re-execute, If values from dependency array are updated as well as it will execute componentWillUnmount for clearing sideEffects.
🌐
Reddit
reddit.com › r/reactjs › does useeffect completely replace mounting lifecycle ?
r/reactjs on Reddit: Does useEffect completely replace mounting lifecycle ?
May 15, 2022 -

Hi, I'm wondering if useEffect replaces the lifecycle while using componentDidMount(), componentWillMount(), etc. Are they worth learning?

🌐
DEV Community
dev.to › gkhan205 › use-componentwillunmount-with-react-hooks-4be2
Use componentWillUnmount with React Hooks - DEV Community
May 2, 2020 - Hello everyone, today we will see how can we use componentWillUnmount with react hooks. So as you all know that with React Hooks we don't have lifecycle methods that are present in React Class Component, on the other hand, we have pre-built hooks provided by React some of them are useState, useEffect, useRef, useContext etc.