DEV Community 👩‍💻👨‍💻

Jakub Jadczyk
Jakub Jadczyk

Posted on

React life-cycle events in functional components

Functional components are easier to deal with. We need less code to get the same result comparing to Class components.

So the question is: how to deal with life-cycle events? The answer is hook useEffect.
This hook is equivalent to life cycle methods componentDidMount, componentDidUpdate and componentWillUnmount.

import React, { useEffect } from 'react';
const ourComponent => () => {
   useEffect( () => {
      // Anything in here is fired on component mount.
   });
}
Enter fullscreen mode Exit fullscreen mode

How many times this code inside will be executed depends on array of dependencies passed as a second argument.
If we don't pass any array (even empty) our effect will be fired with every render.
If we want to execute effect only on first render we need to pass empty array.

useEffect(() => {
   console.log("Effect has been called");
}, []) // Empty array as dependency, useEffect is invoked once
Enter fullscreen mode Exit fullscreen mode

If we pass value inside array in second parameter, the effect will be fired only when the value from previous render is not the same.

const[state, setState] = useState(0); 
     useEffect(() => { 
          console.log(state); 
          // since we are using state, we have 
          // to pass it as a dependency 
     }, [state]) 
Enter fullscreen mode Exit fullscreen mode

We can manage componentWillUnmount adding return function inside effect. Everything inside return will be fired when component unmounts.

const ComponentExample => () => {
    useEffect(() => {
        return () => {
            // Anything in here is fired on component unmount.
        }
    }, [])
}
Enter fullscreen mode Exit fullscreen mode

There is also possibility to use it in both situations. componentDidMount and componentWillUnmount

const ComponentExample => () => {
    useEffect(() => {
        // Anything in here is fired on component mount.
        return () => {
            // Anything in here is fired on component unmount.
        }
    }, [])
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Let's Get Hacking

Join the DEV x Linode Hackathon 2022 and use your ingenuity and creativity to build using Linode.

Join the Hackathon <-