DEV Community

Ashish Kankal
Ashish Kankal

Posted on

Lifecycle methods alternative in React functional components

Lifecycle methods are functions that are called during different stages of a component's lifecycle. They can be used to perform tasks such as fetching data, setting up event listeners, and cleaning up resources.

Here are some of the most common lifecycle methods:

  • componentDidMount(): This method is called after the component has been mounted to the DOM. It is a good place to do things like fetch data or set up event listeners.

  • componentDidUpdate(): This method is called after the component has been updated. It is a good place to do things like re-render the component or update the state.

  • componentWillUnmount(): This method is called before the component is unmounted from the DOM. It is a good place to do things like clean up resources or unsubscribe from event listeners.

How to reproduce the behaviour using hooks?

In React 16.8, React introduced Hooks, which are a new way to use state and lifecycle features in functional components. Hooks are designed to be more flexible and easier to use than lifecycle methods, so they are the recommended way to write React components.

Executing code on mount using hook (componentDidMount)

import React, { useEffect } from 'react';

const MyFunctionalComponent = () => {
  useEffect(() => {
    // This code will run only once when the component mounts
    // Perform any side effects here, such as API calls or event subscriptions

  }, []); // The empty dependency array ensures that this effect only runs once

  return (
    <div>Hello World!</div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Remember: The Empty Dependency Array

Executing code on props update using hook (componentDidUpdate)

import React, { useEffect } from 'react';

const MyFunctionalComponent = ({prop1, prop2}) => {
  useEffect(() => {
    // The dependency array ensures that this effect runs when either prop1 or prop2 is updated.

  }, [prop1, prop2]);

  return (
    <div>Hello World!</div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Executing code before unmount using hook (componentDidUpdate)

import React, { useEffect } from 'react';

const MyFunctionalComponent = () => {
  useEffect(() => {

    return () => {
      // This code will run when the component is unmounted
      // Perform any cleanup tasks here, such as canceling API requests or unsubscribing from events
    };

  }, []);

  return (
    <div>Hello World!</div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Example illustrating all the three side-effects together

const UpCounterExample =()=> {
  const [count, setCount] = useState(0);

  useEffect(() => {
    // This effect will run once after the component mounts,
    // and then again whenever the `count` state variable changes.
    const interval = setInterval(() => {
      setCount(count + 1);
    }, 1000);

    return () => clearInterval(interval);
  }, [count]);

  return (
    <div>
      <h1>Counter</h1>
      <p>Count: {count}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, the useEffect hook is used to create a timer that increments the count state variable every second. The useEffect hook takes two arguments: a callback function and an array of dependencies. The callback function is executed whenever any of the dependencies change. In this case, the only dependency is the count state variable.

Conclusion

Hooks are a powerful tool that can be used to improve the performance and readability of React components. They allow you to perform side effects in a way that is both predictable and efficient. By understanding how hooks work, you can write more reusable and maintainable code.

Here are some additional points to consider:

  • Hooks are a relatively new feature in React, so there may be some learning curve involved. However, the benefits of using hooks are well worth the effort.
  • There are a number of different hooks available, each with its own specific purpose. It is important to choose the right hook for the job.
  • Hooks can be used to improve the performance of React components by reducing the number of unnecessary re-renders.
  • Hooks can also be used to improve the readability of React components by making it easier to understand how they work.

If you are new to React, I encourage you to learn more about hooks. They are a powerful tool that can help you write better React code.

Top comments (0)