Sign Up

Sign In

Forget Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

You must login to ask question.

How to use componentWillMount() in React Hooks?

  • 0

In the official docs of React it mentions –

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

My question is – how can we use the componentWillMount() lifecyle method in a hook?

Click to rate this post!
[Total: 0 Average: 0]
Share This Post
Share
  1. You cannot use any of the existing lifecycle methods (componentDidMountcomponentDidUpdatecomponentWillUnmount 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 componentDidMountcomponentDidUpdate, 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.

    componentDidMount() {
      window.addEventListener('mousemove', () => {})
    }
    
    componentWillUnmount() {
      window.removeEventListener('mousemove', () => {})
    }

    Hook equivalent of above code will be as follows

    useEffect(() => {
      window.addEventListener('mousemove', () => {});
    
      // returned function will be called on component unmount 
      return () => {
        window.removeEventListener('mousemove', () => {})
      }
    }, [])
    • 0
Leave an answer

Leave an answer

Browse

close