DEV Community

Jakub Jadczyk
Jakub Jadczyk

Posted on

1

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay