19 Feb 2024




Intermediate

In React, functional components are a way to define components using JavaScript functions rather than classes. With the introduction of React Hooks, functional components can now manage state and lifecycle events, similar to class components. However, instead of lifecycle methods, functional components use useEffect hook to handle side effects and perform tasks at specific points in the component's lifecycle.

Here's a breakdown of the typical lifecycle events in a functional component using the useEffect hook:

  1. Mounting:

    • useEffect with an empty dependency array ([]):
      • This is similar to componentDidMount in class components.
      • Runs once after the initial render.
      • Used for tasks that need to be performed once when the component is first mounted.
    useEffect(() => {
      // componentDidMount logic
      return () => {
        // componentWillUnmount logic (cleanup)
      };
    }, []);
    
  2. Updating:

    • useEffect with a dependency array:
      • This is similar to componentDidUpdate in class components.
      • Runs whenever the specified dependencies (variables, props, etc.) change.
      • Used for tasks that need to be performed when the component updates.
    useEffect(() => {
      // componentDidUpdate logic
      return () => {
        // componentWillUnmount logic (cleanup)
      };
    }, [dependency1, dependency2]);
    
  3. Unmounting:

    • Cleanup in the return function of useEffect:
      • This is similar to componentWillUnmount in class components.
      • Runs when the component is about to be unmounted.
      • Used for cleanup tasks (e.g., removing event listeners or clearing intervals).
    useEffect(() => {
      // componentDidMount or componentDidUpdate logic
    
      return () => {
        // componentWillUnmount logic (cleanup)
      };
    }, [dependency]);
    

Remember that functional components with hooks provide a more concise and readable way to handle component lifecycle events, making it easier to manage state and side effects. The useEffect hook is a powerful tool that covers the functionality of multiple lifecycle methods in class components.

reactjs
lifecycle
useeffect