19 Feb 2024
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:
-
Mounting:
useEffectwith an empty dependency array ([]):- This is similar to
componentDidMountin class components. - Runs once after the initial render.
- Used for tasks that need to be performed once when the component is first mounted.
- This is similar to
useEffect(() => { // componentDidMount logic return () => { // componentWillUnmount logic (cleanup) }; }, []); -
Updating:
useEffectwith a dependency array:- This is similar to
componentDidUpdatein class components. - Runs whenever the specified dependencies (variables, props, etc.) change.
- Used for tasks that need to be performed when the component updates.
- This is similar to
useEffect(() => { // componentDidUpdate logic return () => { // componentWillUnmount logic (cleanup) }; }, [dependency1, dependency2]); -
Unmounting:
- Cleanup in the return function of
useEffect:- This is similar to
componentWillUnmountin class components. - Runs when the component is about to be unmounted.
- Used for cleanup tasks (e.g., removing event listeners or clearing intervals).
- This is similar to
useEffect(() => { // componentDidMount or componentDidUpdate logic return () => { // componentWillUnmount logic (cleanup) }; }, [dependency]); - Cleanup in the return function of
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.